如何在 Javascript 中更改 Array 对象的值

How to change the value of an Array object in Javascript

我有一个数组对象调用 listOfObjects。

[{"name":"A", "data":"[{"value1":"1","value2":"2"}]"},
 {"name":"B", "data":"[{"value1":"1","value2":"2"}]"}]

我想要做的是将一个对象插入到数组所在的数组中 empty.If 数组不为空然后检查里面的项目。如果项目已经存在,则对项目进行更新,否则将其添加到数组中。下面是我的代码

  var searchName= "A"; 
  if (listOfObjects.length > 0) {
            for (var i = 0; i < listOfObjects.length; i++) {
                if (listOfObjects[i].name == searchName) {
                    listOfObjects[i].data = data;
                    break;
                } else {
                    insert = {
                        'name': searchName,
                        'data': data
                    };
                    listOfObjects.push(insert);
                }
            }
    } else {
        insert = {
            'name': searchName,
            'data': data
        };
        listOfObjects.push(insert);
   }

当我 运行 它时,即使 A 已经存在,它也会更新现有项目,但还会向 listOfObjects 添加一次。无论如何可以实现我想要的吗?谢谢..

问题是您要插入数组内部,您的for 循环寻找匹配项。相反,请记住您是否看到了匹配项,如果没有,则在循环之后插入。也没有理由进行 length 检查,也没有理由重复您的插入逻辑:

var searchName= "A"; 
var found = false;
for (var i = 0; !found && i < listOfObjects.length; i++) {
    if (listOfObjects[i].name == searchName) {
        listOfObjects[i].data = data;
        found = true;
    }
}
if (!found) {
    listOfObjects.push({
        'name': searchName,
        'data': data
    });
}

请注意,如果您愿意,可以使用 Array#find(可以为旧浏览器填充)来查找条目而不是 for 循环:

var searchName= "A"; 
var entry = listOfObjects.find(function(entry) {
    return entry.name == searchName;
});
if (entry) {
    entry.data = data;
} else {
    listOfObjects.push({
        'name': searchName,
        'data': data
    });
}

首先改变这个

[{"name":"A", "data":"[{"value1":"1","value2":"2"}]"},
 {"name":"B", "data":"[{"value1":"1","value2":"2"}]"}]

来自

[{"name":"A", "data":[{"value1":1,"value2":2}]},
 {"name":"B", "data":[{"value1":"1","value2":"2"}]}];

因为您的列表将 throw Uncaught SyntaxError: Unexpected identifier

编写另一个简单的函数来获取带有选定 searchName 的项目 listOfObjects[i]。这里 'getSearchObject()' 函数检查 searchName 是否存在,然后添加或更新数组。

addOrRemoveItem() {
    let listOfObjects = [
      { "name": "A", "data": "[{'value1':'1','value2':'2'}]" },
      { "name": "B", "data": "[{'value1':'1','value2':'2'}]" }
    ],
      data = '[{"value1":"1","value2":"2"}]';
    var searchName = "C";
    if (listOfObjects.length > 0) {
      let searchObj = this.getSearchObject(listOfObjects, searchName);
      if (searchObj) {
        searchObj.data = data;
      } else {
        let insert = {
          "name": searchName,
          "data": data
        }
        listOfObjects.push(insert);
      }
    } else {
      let insert = {
        "name": searchName,
        "data": data
      }
      listOfObjects.push(insert);
    }
  }

  getSearchObject(objArr, searchKey) {
    var obj = null;
    for (let i = 0; i < objArr.length; i++) {
      if (objArr[i].name === searchKey) {
        obj = objArr[i];
      }
    }
    return obj;
  }

一个通用的解决方案,可以识别旧的 JS 引擎(filter 而不是 find),但总是假设通过了一个独特的项目列表,可以像这样实现...

function updateList(itemList, item) { // - always assume a list of unique items.
  var
    itemName = item.name,
    listItem = itemList.filter(function (elm) { // - assume `filter`, not find`.
      return (elm.name === itemName); // - find/get existing list  item by name.
    })[0];

  if (listItem) {
    listItem.data = item.data;
  } else {
    itemList.push(item)
  }
}


var list = [
  { "name": "A", "data": [ { "value1": "A1", "value2": "A2" }] },
  { "name": "B", "data": [ { "value1": "B1", "value2": "B2" }] },
  { "name": "C", "data": [ { "value1": "C1", "value2": "C2" }] }
];

console.log('list : ', list);


updateList(list,  { "name": "D", "data": [ { "value1": "D1", "value2": "D2" }] });

updateList(list,  { "name": "B", "data": [ { "value1": "b_1", "value2": "b_2", "value3": "b_3" }] });
updateList(list,  { "name": "C", "data": [ { "value3": "C3" }] });

console.log('list : ', list);
.as-console-wrapper { max-height: 100%!important; top: 0; }