js 匹配更新数组中的json对象
时间: 2023-08-06 10:04:10 浏览: 232
可以使用 Array.prototype.findIndex() 方法找到要更新的 JSON 对象在数组中的索引位置,然后使用 Array.prototype.splice() 方法替换该位置的元素。示例代码如下:
```javascript
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
// 要更新的 JSON 对象
const updatedObj = { id: 2, name: 'Jack' };
// 找到要更新的 JSON 对象在数组中的索引位置
const index = arr.findIndex(obj => obj.id === updatedObj.id);
if (index !== -1) {
// 使用 splice() 方法替换该位置的元素
arr.splice(index, 1, updatedObj);
}
console.log(arr); // [{ id: 1, name: 'John' }, { id: 2, name: 'Jack' }, { id: 3, name: 'Bob' }]
```
上述代码中,我们首先定义了一个数组 `arr`,它包含了三个 JSON 对象。接着定义了一个要更新的 JSON 对象 `updatedObj`,它的 `id` 属性值为 `2`,`name` 属性值为 `Jack`。然后使用 `Array.prototype.findIndex()` 方法找到了 `updatedObj` 在 `arr` 中的索引位置,并将其保存在变量 `index` 中。最后使用 `Array.prototype.splice()` 方法替换了该位置的元素,实现了更新操作。
阅读全文
相关推荐















