我有一个数组 - 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/