首页 > 解决方案 > 对象不使用扩展运算符替换

问题描述

我想使用扩展运算符将现有对象替换为新的更新字段。但我没有得到正确的结果。

下面是我的两个对象。

let obj1 = [
  {
    "id": 1,
    "name": "Michel",
    "age": 34,
    "email": "michel@gmail.com"
  },
  {
    "id": 2,
    "name": "Abby",
    "age": 40,
    "email": "abby@gmail.com"
  },
  {
    "id": 3,
    "name": "Gary",
    "age": 40,
    "email": "abby@gmail.com"
  }
]

let newObj = {
  "id": 3,
  "name": "Gary",
  "age": 23,
  "email": "gary@gmail.com"
}

我可以用 .map 做到这一点。下面是我的代码。

let result = obj1.map(item => {
  if (item.id === newObj.id) {
    return {...item, ...newObj};
  }
  return item;
});

但我不想运行循环,只想通过扩展运算符来实现。

传播的例子。这是行不通的。它不是替换对象。而是再创造一个。

[...obj1,  newObj];

有人能帮我吗?

JSBIN 代码片段

标签: javascriptangularreactjsecmascript-6

解决方案


扩展语法不会像您使用它那样替换数组中的对象。使用地图是最简单易懂的方式。但是,如果要使用spread syntax,首先需要找到要替换的索引,然后在数组上使用切片

let obj1 = [
  {
    "id": 1,
    "name": "Michel",
    "age": 34,
    "email": "michel@gmail.com"
  },
  {
    "id": 2,
    "name": "Abby",
    "age": 40,
    "email": "abby@gmail.com"
  },
  {
    "id": 3,
    "name": "Gary",
    "age": 40,
    "email": "abby@gmail.com"
  }
]

let newObj = {
  "id": 3,
  "name": "Gary",
  "age": 23,
  "email": "gary@gmail.com"
}

const idx = obj1.findIndex(item => item.id === newObj.id);

obj1 = [...obj1.slice(0, idx), newObj, ...obj1.slice(idx + 1)];

console.log(obj1);


推荐阅读