传播运算符,用于在对象中的数组内部分配数据

时间:2018-12-28 15:26:34

标签: javascript spread-syntax

我需要使用传播运算符在以下状态内更新数据。 必须这样进行: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": ""
};

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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

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