I have below array of objects with each object having a projects attribute which further has its array of objects.
const data = [
{
"title": "Release",
"projects": [
{
"name": "Server",
"result": {
"success": 0,
"failure": 100
},
}
]
},
{
"title": "Payments",
"projects": [
{
"name": "Platform1",
"result": {
"success": 100,
"failure": 0
}
},
{
"name": "Platform2",
"result": {
"success": 50,
"failure": 50,
}
}
]
}
]
I wanted to iterate through it and get the result as follows. name is nothing but concatenation of title and name from above data.
const result = [
{
name: 'Release-Server',
success: 0,
failure: 100,
},
{
name: 'Payments-Platform1',
success: 100,
failure: 0,
},
{
name: 'Payments-Platform2',
success: 50,
failure: 5,
},
];
I have tried below ways but not able to figure out how to get exactly the result as shown above. can someone pls help on this.
data.forEach(prj => {
prj.projects.forEach((project) => {
// unable to get how to push these details into a new array of object
})
});
2 Answers 2
You can do the following (Make sure you add checks for null/undefined references)
const data = [{
"title": "Release",
"projects": [{
"name": "Server",
"result": {
"success": 0,
"failure": 100
},
}]
},
{
"title": "Payments",
"projects": [{
"name": "Platform1",
"result": {
"success": 100,
"failure": 0
}
},
{
"name": "Platform2",
"result": {
"success": 50,
"failure": 50,
}
}
]
}
];
const result = data.flatMap(item =>
item.projects.map(project => ({
name: `${item.title}-${project.name}`,
success: project.result.success,
failure: project.result.failure
})));
console.log(result);
1 Comment
success and failure explicitly you can also just spread out project.result. This is usefull when at a later stage you want to add a property to the result object. This way you don't have to change the loop to also include that new propertyYou should use flatMap first because you have will change the number of elements (you start with 2, you end with 3) and inside a simple map to convert 1:1 each project into your final object.
Working Demo
const data = [{
"title": "Release",
"projects": [{
"name": "Server",
"result": {
"success": 0,
"failure": 100
},
}]
},
{
"title": "Payments",
"projects": [{
"name": "Platform1",
"result": {
"success": 100,
"failure": 0
}
},
{
"name": "Platform2",
"result": {
"success": 50,
"failure": 50,
}
}
]
}
];
var groupedData = data.flatMap((el) =>
el.projects.map((proj) => ({
name: el.title + "-" + proj.name,
success: proj.result.success,
failure: proj.result.failure,
}))
);
console.log(groupedData);
Comments
Explore related questions
See similar questions with these tags.
mapandflatMapmight be helpful here.