转换为键值对

3

这是我拥有的对象。

    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
        }
    ]

它只显示了第一个键值,第二个键值缺失了,这里我做错了什么?
7个回答

3
问题在于,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})))

1
您可以使用以下代码来完成它。

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

const updatedArr = upToPaidCost.map((item)=>{
  return {"key":Object.keys(item)[0],"value":item[Object.keys(item)[0]]}
})



console.log(updatedArr)

这个链接中的测试 https://replit.com/join/taxflvkp-gauthamjm007


FYI,你可以在这里创建可运行的代码片段。 - georg

1
我看到原始数组中的每个项目都是一个对象。因此,您可以这样做,而不是迭代。

Besides, according to the expected output, value is a number. So you can cast from string to number like this.

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

const result = upToPaidCost.map(o => {
  const [key, value] = Object.entries(o)[0];
  return {key, value: +value};
});
console.log(result);


0

我喜欢我的代码更易读。另一种答案。

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

const final = upToPaidCost.map((item)=>{
  const key = Object.keys(item)[0]
  return { key, value: item[key] }
})

console.log(final)


0

Object.entries(...upToPaidCost) 等于 Object.entries({ 'Labour Cost': '54000' }),所以结果是错误的。

我们需要先使用 reduce 方法将对象合并:

const upToPaidCost = [{ "Labour Cost": "54000" }, { "Material Cost": "24900" }];
let arr = [];
const conbineObj = upToPaidCost.reduce(
  (res, item) => ({ ...res, ...item }),
  {}
);
for (const [key, value] of Object.entries(conbineObj)) {
  arr.push({ key: key, value: value });
}
console.log(upToPaidCost);
console.log(arr)

0

为什么你的代码片段会这样运行?

在这一行中

for (const [key, value] of Object.entries(...upToPaidCost))

你正在传播 upToPaidCost,然后要求 Object.entries 将其作为类似数组的返回。

因此从技术上讲,它是这样的:

Object.entries({ 'Labour Cost': '54000' }, { 'Material Cost': '24900' })

正如您所看到的,您正在将2个对象(参数)传递给Object.entries,但它只接受其中一个(第一个)

因此,这行代码将被解释为:

for (const [key, value] of [['Labour Cost': '54000']])`

如何修正代码片段?

你可以将Object.entries(...upToPaidCost)替换为Object.entries(upToPaidCost),这样Object.entries只接收一个简单参数。

然后在循环中,你可以将每个对象推入arr

你可以在这里查看:

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

    for (const [arrayindex, innerObject] of Object.entries(upToPaidCost)) {
        arr.push(innerObject);
    }
    console.log(upToPaidCost);
    console.log(arr);

正如您所看到的,这些值仍然是字符串。如果您想将它们转换为数字,可以获取键和值并创建新对象,然后将它们推送到arr中,就像这样:

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

        for (const [upToPaidCostIndex, innerObject] of Object.entries(upToPaidCost)) {
            const key = Object.keys(innerObject)[0];
            const value = Object.values(innerObject)[0];
            
            arr.push({[key] : +value});
        }
        console.log(upToPaidCost);
        console.log(arr);

更好的解决方案

const upToPaidCost = [ { 'Labour Cost': '54000' }, { 'Material Cost': '24900' } ];
const upToPaidCosts = upToPaidCost.reduce((res, item) => ({...item, ...res}), {});
const arr = Object.entries(upToPaidCosts).map(([key, value]) => ({[key]: +value}))


console.log(upToPaidCost);
console.log(arr);


-1

这里的Object.entries(...upToPaidCost)会移除...
当你想要复制一个对象时,请使用...,例如:const x = {...upToPaidCost};
或者在你的情况下使用Object.entries({...upToPaidCost})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接