Ibrahim Ali
Ibrahim Ali

Reputation: 2513

Merge all arrays inside of an object

let fruit = {
    apple: [1, 2],
    orange: [3, 4],
    banana: [5, 6],
};

let allFruits = fruit.apple.concat(fruit.orange).concat(fruit.banana);

I can do something like this but what if I have like 20 fruit... Any other way maybe with lodash?

Upvotes: 2

Views: 73

Answers (3)

Behemoth
Behemoth

Reputation: 9340

Here's another vanilla JS solution using .reduce().

const fruit = {
  apple: [1, 2],
  orange: [3, 4],
  banana: [5, 6],
};

console.log(Object.values(fruit).reduce((t, c) => t.concat(...c), []));

Upvotes: 0

raina77ow
raina77ow

Reputation: 106453

For the sake of completeness, here's how one can do it with lodash:

_.flatMap(fruit)

Yep, that simple. Two hidden tricks here:

  • flatMap (unlike flatten) works with Collections, and calls Object.values() for objects anyway
  • it takes _.identity (x => x) as a mapper function by default

Upvotes: 1

Scotty Jamison
Scotty Jamison

Reputation: 13219

No need to use lodash here. All you need to do is get a list of all the object values (with Object.value()), then flatted it (with yourArray.flat())

let fruit = {
    apple: [1, 2],
    orange: [3, 4],
    banana: [5, 6],
};

console.log(Object.values(fruit).flat())

Upvotes: 3

Related Questions