Search code examples
javascriptecmascript-6destructuring

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?


Solution

  • 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}`));