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" let state = {...

问题:

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"

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": ""
};

回答1:

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


回答2:

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


回答3:

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

Otherwise if you are absolutely sure of the structure of state and want to do a simple clone you can do the following:

   let modifiedstate = "data": [{
     ...state.data[0],
     "vehOn": "Finance"
     }],
     "error": ""
   }
  • 发表于 2018-12-30 10:42
  • 阅读 ( 198 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除