扩展运算符在对象的数组内分配数据

Spread operator to assign data inside array in an object

我需要使用扩展运算符更新以下状态中的数据。 必须这样做 data[0] 应该更新为 "vehOn":"Finance"

let state = {
  "data": [{
    "year": "2017",
    "make": "ALFA ROMEO",
    "model": "ILX 4D 2.0 PREMIUM PACKAGE"
  }],
  "error": ""
};

修改后的状态应该是这样的:

let modifiedstate = {
  "data": [{
    "year": "2017",
    "make": "ALFA ROMEO",
    "model": "ILX 4D 2.0 PREMIUM PACKAGE",
    "vehOn": "Finance"
  }],
  "error": ""
};

根据 documentation,我认为实现您的结果的唯一方法是:

let state = {
    "data": [{
        "year": "2017",
        "make": "ALFA ROMEO",
        "model": "ILX 4D 2.0 PREMIUM PACKAGE"
    }],
    "error": ""
};

let modifiedstate  = { "data": [{ ...state.data[0], ...{vehOn: "Finance"} }],
    "error": ""};

console.log(modifiedstate);

如果您的目的是创建一个与状态相同的对象并且您不知道 state 可以拥有哪些属性,您应该寻找一种方法来 deep clone it

否则,如果您完全确定 state 的结构并想做一个简单的克隆,您可以执行以下操作:

   let modifiedstate = "data": [{
     ...state.data[0],
     "vehOn": "Finance"
     }],
     "error": ""
   }

const state = {
  "data": [{
    "year": "2017",
    "make": "ALFA ROMEO",
    "model": "ILX 4D 2.0 PREMIUM PACKAGE"
  }],
  "error": ""
};

console.log("---- state ----");
console.log(state);

const modifiedstate = { ...state,
  data: state.data.map((entry, i) => i === 0 ? ({ ...entry,
    vehOn: "Finance"
  }) : entry)
};

console.log("---- modifiedstate ----");
console.log(modifiedstate);