1

Say I have an object like this:

var families =
[
    { dad: 'bob', mom: 'sue', income: 10 },
    { dad: 'john', mom: 'jane', income: 5 }
];

Is there a fancy way to transform this into the following:

[ 'bob', 'sue', 'john', 'jane' ];

I know I could do it like this:

var people = [];
for (var index = 0; index < families.length; index++)
{
    people.push(families[index].dad);
    people.push(families[index].mom);
}

However I like to use Javascript's build-in array functions whenever possible (filter, map, forEach, etc). The best I could figure is using 'map':

var people = families.map(function(family)
{
    return [family.dad, family.mom];
});

But that doesn't do what I want:

[ [ 'bob', 'sue' ], [ 'john', 'jane' ] ]

Is there any built-in that can do what I want? Thanks!

1
  • 1
    Use a .flat() at the end? Commented Apr 30, 2020 at 0:37

3 Answers 3

1

You can destructure the properties out in the .map, return an array like you're doing, then .flat()ten the array:

var families = [
    { dad: 'bob', mom: 'sue', income: 10 },
    { dad: 'john', mom: 'jane', income: 5 }
];

const names = families
  .map(({ dad, mom }) => [dad, mom])
  .flat();
console.log(names);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use reduce function:

let families =
[
    { dad: 'bob', mom: 'sue', income: 10 },
    { dad: 'john', mom: 'jane', income: 5 }
];

const result = families.reduce((res, item)=> {
return [...res, item.dad, item.mom]
}, [])

console.log(result)

Or just add flat() funtion to map result:

var people = families.map(function(family)
{
    return [family.dad, family.mom];
}).flat();

Comments

0
  • One line code using .map
  • Creating nested array and then using .flat

var families =
[
    { dad: 'bob', mom: 'sue', income: 10 },
    { dad: 'john', mom: 'jane', income: 5 }
];

console.log (families.map(it => [it.dad, it.mom]).flat())

Comments

Your Answer

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.