javascript - 使用 spread 元素合并 javascript 数组中的值

标签 javascript arrays ecmascript-6

我有一个数组 - types - 看起来像这样 -

[
  {"id": 1, "name": "Payment"},
  {"id": 2, "name": "Debit"},
  {"id": 3, "name": "Credit"},
  {"id": 4, "name": "Transaction"}
]

我想将数组转换为另一个数组,如下所示 -

[
  {"Payment": 1},
  {"Debit": 2},
  {"Credit": 3},
  {"Transaction": 4}
]
<小时/>

当我执行以下操作时,第一个条目总是丢失 -

const typeArray = types === null || types.length === 0 ? [] :
    types.map((type) => {
        const id = type.id;
        const name = type.name;
        return {[name]: id};
    })
        .reduce((prev, curr) => [...prev, curr]);

我总是得到这样的输出 -

[
  {"Debit": 2},
  {"Credit": 3},
  {"Transaction": 4}
]
<小时/>

当我改为使用 -

    .reduce((prev, curr) => [prev, curr]);

我得到一个嵌套数组,但所有元素都存在。数组看起来像这样 -

[
   [
      [
        {"Payment":1},
        {"Debit":2}
      ],
      {"Credit":3}
   ],
   {"Transaction":4}
]

我该怎么做。是否有类似 RxJS 中的 flatMap() 的东西,我可以将所有数组合并到一个数组中?

最佳答案

您应该使用接受回调函数作为参数的map方法,以获得更干净的解决方案。

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

let array=[
  {"id": 1, "name": "Payment"},
  {"id": 2, "name": "Debit"},
  {"id": 3, "name": "Credit"},
  {"id": 4, "name": "Transaction"}
]
array=array.map(function(item){
  return {[item.name]:item.id};
});
console.log(array);

或使用箭头函数:

array=array.map(item=> {[item.name]:item.id});

此外,您还可以通过以下方式使用reduce函数:

let array=[
      {"id": 1, "name": "Payment"},
      {"id": 2, "name": "Debit"},
      {"id": 3, "name": "Credit"},
      {"id": 4, "name": "Transaction"}
    ]
array=array.reduce((arr,item)=>{
    arr.push({[item.name]:item.id});
    return arr;
},[]);
console.log(array);

关于javascript - 使用 spread 元素合并 javascript 数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46319706/

相关文章:

javascript - Backbone.js 比较函数,如何实现降序?

javascript - 将字符串转换为 Angular 8 中的枚举值

javascript - 使用 ES6 访问参数对象

javascript - 如何简化组件中多余的 React 代码?

javascript - 如何在持久的 NextJS React Audio Player 组件中捕获 Mobx 可观察更新?

javascript - 如何从 ES6 类中的 getter 函数返回构造函数参数值

javascript - 对象被 JavaScript 中的后续对象覆盖

javascript - 如何在 MERN 堆栈中向用户显示错误

c - 使用结构 : tshirtArray[50] in the structure or 50x structname. tshirt1,2,3 等

javascript - 在不使用循环的情况下检测二维网格上的鼠标碰撞