1

How to retrieve values of objects into a single array.

var arrayOjObjects =  {
  "Fruits": ["Banana", "Apple"],
  "Vegetables": ["Carrot", "Chilli"],
  "Drinks": ["Coco", "Pepsi"]
}
Output = ["Banana", "Apple", "Carrot", "Chilli", "Coco", "Pepsi"]

Tried Object.values(arrayOjObjects) but it is giving multiple arrays. Any inputs on this?

Phil
  • 141,914
  • 21
  • 225
  • 223
Balanjaneyulu K
  • 2,556
  • 5
  • 21
  • 32
  • 2
    Add [`.flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) to flatten the array – Phil May 10 '22 at 05:41

2 Answers2

1

You could take an array of the keys and then reduce it to the desired result:

var arrayOfObjects = {
  "Fruits": ["Banana", "Apple"],
  "Vegetables": ["Carrot", "Chilli"],
  "Drinks": ["Coco", "Pepsi"]
}

const output = Object.keys(arrayOfObjects).reduce((output, key) => {
  output.push(...arrayOfObjects[key]);
  return output;
}, [])

console.log(output)
//Output = ["Banana", "Apple", "Carrot", "Chilli", "Coco", "Pepsi"]
Aneesh
  • 1,673
  • 2
  • 14
1

Use flat, like:

Object.values(arrayOjObjects).flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

CD..
  • 68,981
  • 24
  • 147
  • 156