1

I have a data with structure like this:

const arr1 = [
 {
 name: 'a',
 subObjects: [
 { name: 'a1', age: 10 },
 { name: 'a2', age: 12 },
 ],
 },
 { name: 'b', age: 23 },
 {
 name: 'c',
 subObjects: [
 { name: 'c1', age: 30 },
 { name: 'c2', age: 32 },
 ],
 },
 ...
];

So, the array contains an array of objects, some objects also contain nested level object subObjects which contains the same structure as parent. Overall some 1st level object in array can have maximum two levels of nest (like above example shows).

Now, I need to have an array that gather all names of objects from above array, something like:

[
 { name: 'a' },
 { name: 'a1' },
 { name: 'a2' },
 { name: 'b' },
 { name: 'c' },
 { name: 'c1' },
 { name: 'c2' },
];

This is what I tried:

const arr1 = [
 {
 name: 'a',
 subObjects: [
 { name: 'a1', age: 10 },
 { name: 'a2', age: 12 },
 ],
 },
 { name: 'b', age: 23 },
 {
 name: 'c',
 subObjects: [
 { name: 'c1', age: 30 },
 { name: 'c2', age: 32 },
 ],
 },
];
const arr2 = arr1.map((obj) => {
 return obj.subObjects ? obj.subObjects.flat() : obj.name;
});
console.log(arr2.flat());

But the output lost the 1st level object names for those who has nested objects. So, what is the best way to achieve what I need?

Zsolt Meszaros
23.3k19 gold badges60 silver badges70 bronze badges
asked Nov 26, 2020 at 13:38

1 Answer 1

1

You could use a recursive flatMap to do it (with a little help from the spread oparator!):

const arr1 = [{name: 'a', subObjects:[{name: 'a1', age: 10}, {name: 'a2', age: 12},]}, {name: 'b', age: 23}, {name: 'c', subObjects:[{name: 'c1', age: 30}, {name: 'c2', age: 32},]}];
const recursiveFlat = (arr) => arr.flatMap(
 a => a.subObjects 
 ? [{name: a.name}, ...recursiveFlat(a.subObjects)] 
 : {name: a.name});
console.log(recursiveFlat(arr1));

This will work with any depth of nesting.

answered Nov 26, 2020 at 13:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.