Christian Bongiorno
Christian Bongiorno

Reputation: 5648

Javascript array de-structuring and Object.entries

It's pretty simple: Object.entries is supposed to produce and Array of key, value pairs.. As such, I would expected this code to destructure

[{
  id: 1,
  name: "christian"
},{
  id : 2,
  name: "bongiorno"
}].map(Object.entries).forEach(([k,v]) => console.log(`${k}: ${v}`));

into producing:

id:1 name:christian
id:2 name:bongiorno

But it doesn't. I get, instead:

id,1: name,christian
id,2: name,bongiorno

What did I miss?

Upvotes: 2

Views: 823

Answers (2)

nem035
nem035

Reputation: 35481

The output is correct but your definition is slightly off, you're missing an array level (array of arrays).

Object.entries is supposed to produce an array of arrays of key, value pairs.

console.log(
  Object.entries({
    id: 1,
    name: 'test'
  })
)

To achieve what you want, you can just update your log to account for nested arrays:

[{
  id: 1,
  name: "christian"
},{
  id : 2,
  name: "bongiorno"
}]
  .map(Object.entries)
  .forEach(([k, v]) => console.log(
    `${k.join(':')} ${v.join(':')}`
  ));

Or maybe you meant to flatten each array?:

[{
  id: 1,
  name: "christian"
},{
  id : 2,
  name: "bongiorno"
}]
  .map(Object.entries)
  .reduce((arr, curr) => arr.concat(curr), [])
  .forEach(([k,v]) => console.log(`${k}: ${v}`));
  

Upvotes: 3

Bergi
Bergi

Reputation: 664297

Let's try to drop the map and forEach and see what you did with each of the objects:

let [k, v] = Object.entries({
  id: 1,
  name: "christian"
});
console.log(`${k}: ${v}`);

let [k, v] = Object.entries({
  id : 2,
  name: "bongiorno"
});
console.log(`${k}: ${v}`);

Now if we expand the Object.entries call, this becomes

let [k, v] = [
  ["id", 1],
  ["name", "christian"]
];
console.log(`${k}: ${v}`);

let [k, v] = [
  ["id", 2],
  ["name", "bongiorno"]
];
console.log(`${k}: ${v}`);

which quite accurately reflects what you're seeing - k and v are getting assigned arrays.

You will need to nest two loops:

const arr = [{
  id: 1,
  name: "christian"
}, {
  id: 2,
  name: "bongiorno"
}];
for (const obj of arr)
    for (const [k, v] of Object.entries(obj))
        console.log(k+": "+v);

Upvotes: 2

Related Questions