Javascript数组解构和Object.entries [英] Javascript array de-structuring and Object.entries

查看:169
本文介绍了Javascript数组解构和Object.entries的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简单:Object.entries 应该产生键值对的Array..因此,我希望这段代码能解构

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

投入生产:

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

但事实并非如此.我得到了:

But it doesn't. I get, instead:

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

我想念什么?

推荐答案

输出正确,但是您的定义稍有偏离,您缺少数组级别(数组数组).

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

Object.entries应该产生键,值对数组的数组.

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

这篇关于Javascript数组解构和Object.entries的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆