gpt4 book ai didi

javascript - 转换为键值对

转载 作者:行者123 更新时间:2023-12-04 01:04:01 25 4
gpt4 key购买 nike

这是我的对象

    const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ];
let arr = [];


for (const [key, value] of Object.entries(...upToPaidCost)) {
arr.push({ key: key, value: value });
}
console.log(upToPaidCost)
console.log(arr);

预期输出:

    [
{
key: "Labour Cost",
value: 54000
},
{
key: "Material Cost",
value: 24900
}
]

它只显示第一个键值,第二个键值丢失,我在这里做错了什么?

最佳答案

问题是,Object.entries 采用单个对象,而您有一个对象数组。这就是为什么你需要两个循环:

const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ];
let arr = [];


for (const obj of upToPaidCost) {
for (const [key, value] of Object.entries(obj)) {
arr.push({key, value});
}
}

console.log(arr);

或两个嵌套的map:

arr = upToPaidCost.flatMap(obj =>
Object.entries(obj).map(([key, value]) => ({key, value})))

关于javascript - 转换为键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67104732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com