简体   繁体   English

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

[英]Spread operator to assign data inside array in an object

I need to update the data inside the below state using spread operator.我需要使用扩展运算符更新以下状态内的数据。 It has to be done such a way that data[0] should be updated with "vehOn":"Finance"必须以这样的方式完成data[0]应使用"vehOn":"Finance"

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

Modfied state should be like:修改后的状态应该是:

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

As per documentation the only way I can see to achieve your result is:根据文档,我可以看到实现结果的唯一方法是:

 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);

 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);

If your intention is to create an object that is identical to state and you don't know what properties state can have you should look for a way to deep clone it如果您的意图是创建一个与 state 相同的对象,并且您不知道state可以拥有哪些属性,那么您应该寻找一种方法来深度克隆它

Otherwise if you are absolutely sure of the structure of state and want to do a simple clone you can do the following:否则,如果您绝对确定state的结构并想要进行简单的克隆,则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM