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
  • 157,677
  • 23
  • 242
  • 245
Balanjaneyulu K
  • 3,660
  • 5
  • 24
  • 45
  • 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,720
  • 4
  • 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..
  • 72,281
  • 25
  • 154
  • 163