不能在JSON对象中添加新的键值对,请有人帮我

问题描述

我正在尝试在下面的JSON对象中添加键值对,但是它以错误的方式添加,有什么方法可以向每个对象添加新的键值对,这将有助于我完成要求

JSON如下:

var object =[
      {
         "asdf":"","fdrtf":"869966","hdhfhfh":"utytut","Cat":"A"
         
      },{
         "hjhj":"","hfhfhf":"h","hhfh":"hfjfhdj","cat":"B"
         
      },"cat":"B"
      }
]

code i am using to add the new key value pair :
for (let i = 0; i < object.length; i++) {
            object[i]['ABC'] = [i];
        }

实际上应该是:

var object =[
      {
         "asdf":"","Cat":"A","ABC": "0"
         
      },"cat":"B","ABC": "1"
         
      },"cat":"B"
         "ABC": "2"
      }
]

我得到的最终值如下:

["0":{
         "hjhj":"",},"1":{
         "asdf":"","Cat":"A"
         
   },"2":{
       "hjhj":"","cat":"B"
   }
  ]

请有人帮我获得期望值,真的需要它

解决方法

您粘贴的代码看起来不错。但是您正在将数组分配给ABC属性。

删除数组,然后分配值。

for (let i = 0; i < object.length; i++) {
        object[i]['ABC'] = i
}

工作示例:

var object = [
    {
        "asdf": "","fdrtf": "869966","hdhfhfh": "utytut","Cat": "A"

    },{
        "hjhj": "","hfhfhf": "h","hhfh": "hfjfhdj","cat": "B"

    },"cat": "B"
    }
]

for (let i = 0; i < object.length; i++) {
    object[i]['ABC'] = i
}

console.log(object);

//Use JSON.stringify if you need Json string
console.log(JSON.stringify(object));

使用ES6 map和传播算子

var object = [
    {
        "asdf": "","cat": "B"
    }
]

let updatedObject = object.map( (item,index) => ({...item,'ABC': index}));
console.log(updatedObject);

//Use JSON.stringify if you need Json string
console.log(JSON.stringify(updatedObject));