如何为给定示例在对象内添加字符串

How To Add A String Inside An Object For The Given Example

您好,我正在寻找在给定的 object.Any 中添加字符串的最佳方法,我们将不胜感激

我的字符串是 'created'

下面是我的数据

{
    "id": "222",
    "list": [
        {
            "name": "Tony",
      
        }
    ], 

我正在尝试像这样在数据中插入 'created'

 {
    "id": "222",
    "list": [
        {
            "name": "Tony",
            "type":"created"
      
        }
    ]

您提供的字符串看起来很像 JSON 数据。您可以使用 JSON.parse(string) 方法将 JSON 字符串转换为实际的 javascript 对象。

有了这个对象,我们就可以查询它的 list 属性 - 在你的例子中是一个对象数组 - 并向每个对象添加一个新的 属性 type的数组元素。最后一步是使用 JSON.stringify(object) 方法将对象转换回 JSON 字符串。

这是一个例子:

let str = `{
    "id": "222",
    "list": [
        {
            "name": "Tony" 
        }
    ]
  }`;
let data = JSON.parse(str);
data.list.forEach(element => {
  element.type = "created";
});
str = JSON.stringify(data);
console.log(str);

const myObj = {
    "id": "222",
    "list": [
        {
            "name": "Tony",
  
        }
    ], 
};
myObj.list[0].type = "created";

这是您可以执行此操作的方法。但是你最好使用 indexlist 个项目;

const index = 0; // Or any other way to get this

myObj.list[index].type = "created";