I am trying to filter an array, based on some nested object. I prepared some Fiddle
Input array looks like this:
let arrayOfElements =
[
{
"name": "a",
"subElements":
[
{"surname": 1},
{"surname": 2}
]
},
{
"name": "b",
"subElements":
[
{"surname": 3},
{"surname": 1}
]
},
{
"name": "c",
"subElements":
[
{"surname": 2},
{"surname": 5}
]
}
];
I'm expecting this output , as I have similar data of management.
let filterArray=
[
{
"name": "a",
"subElements":
[
{"surname": 1}
]
},
{
"name": "a",
"subElements":
[
{"surname": 2},
]
},
{
"name": "b",
"subElements":
[
{"surname": 3}
]
},
{
"name": "b",
"subElements":
[
{"surname": 1}
]
},
{
"name": "c",
"subElements":
[
{"surname": 2}
]
},
{
"name": "c",
"subElements":
[
{"surname": 5}
]
}
];
CodePudding user response:
You can do that easily with a reduce:
let arrayOfElements =
[
{
"name": "a",
"subElements":
[
{"surname": 1},
{"surname": 2}
]
},
{
"name": "b",
"subElements":
[
{"surname": 3},
{"surname": 1}
]
},
{
"name": "c",
"subElements":
[
{"surname": 2},
{"surname": 5}
]
}
];
const result = arrayOfElements.reduce((acc, el) => {
for(let subElement of el.subElements){ //For each of the subelements
acc.push({ //Create a new element only with its data
name: el.name,
subElements: [subElement]
});
}
return acc;
}, [])
console.log(result)
CodePudding user response:
You're looking for flatMap
:
arrayOfElements.flatMap(elem =>
elem.subElements.map(sub => (
{...elem, subElements: [sub]}
))
)