I have a JavaScript object array with the following structure:
somedata = { foo: { bar: [ { baz: [ { someprop: 'a' }, { someprop: 'b' }, { someprop: 'c' } ] }, { baz: [ { someprop: 'd' }, { someprop: 'e' }, { someprop: 'f' } ] } ] } } I want to extract someprop field from this JavaScript object as an array ['a', 'b', 'c', 'd', 'e', 'f']
currently, this is my code logic to extract someprop field as an array:
const result = [] somedata.foo.bar.forEach(x => { x.baz.forEach(y => { result.push(y.someprop) }) }) console.log(result) // prints ["a", "b", "c", "d", "e", "f"] i tried to make the code more reusable by creating a function:
function extractToArray(data, arr, prop) { let result = [] data.forEach(x => { x[arr].forEach(y => { result.push(y[prop]) }) }) return result; } console.log(extractToArray(somedata.foo.bar, 'baz', 'someprop')) But is there a more concise, elegant, cleaner way to achieve this?
Note: possible duplicate covers an array of objects, but this is regarding an array of objects of an array of objects (so a simple map solution won't work).
mapsolution won't work, but it will if you specifically point at the array reference, which is what you're doing currently anyway.mapsolution" won't work. here is a not-so-simple (imho) map solution that would work:somedata.foo.bar.map(i => i.baz).map(i => i.map(j => j.someprop)).flat()