Raziel
Raziel

Reputation: 1566

Unable to flatten an array of objects into a single array

I am trying to flatten an array of objects. The only real informations i require is the arrays compacted into a single array.

The content is as follows:

const content = [
    { "chocolate" : [1] },
    { "banana"    : [5] },
    { "soap"      : [2] },
    { "tea"       : [4] },
];

All i am interested in is the values in the array. So desired result would be:

const result = [1,5,2,4]

I have tried

Object.keys(content).map((val) =>  Object.values(content[val]));

and even tried creating a function

const flatten = ({ children = [], ...rest }) => [rest, ...children.flatMap(flatten)];

and calling it like so:

 console.log(flatten(content));

but no luck. Help?

Upvotes: 0

Views: 136

Answers (5)

Lahcen YAMOUN
Lahcen YAMOUN

Reputation: 691

As easy as this content.flatMap(obj => Object.values(obj)[0])

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

The easiest way is to flat-map the entries, and pop the first value off of the object.

const
  content  = [
    { "chocolate" : [1] },
    { "banana"    : [5] },
    { "soap"      : [2] },
    { "tea"       : [4] },
  ],
  numbers = content.flatMap((obj) => Object.values(obj).pop());

console.log(JSON.stringify(numbers)); // [1, 5, 2, 4]

Upvotes: 1

0stone0
0stone0

Reputation: 43934

You should use flatMap with Object.values:

const content  = [{"chocolate": [1]}, {"banana": [5]},{"soap": [2]},{"tea": [4]}]
const res = content.flatMap(e => Object.values(e)[0]);
console.log(res);

Upvotes: 0

ManuelMB
ManuelMB

Reputation: 1377

const result = content.map(o => Object.values(o).shift()[0])

Upvotes: 0

Nexo
Nexo

Reputation: 2331

// source variable
const content = [{
  "chocolate": [1]
}, {
  "banana": [5]
}, {
  "soap": [2]
}, {
  "tea": [4]
}]
// to store result value
const result = [];
// lopoping though each object and accesing values of pbject using **Object.values(obj)** an array indexes.
content.forEach(val => result.push(Object.values(val)[0][0]));
// Printing result
console.log(result);

Upvotes: 0

Related Questions