向对象添加另一个键...值对

Add another key...value pair to objects

我想为每个对象添加更多键...值对。有可能这样做吗?

现在我的对象看起来像:

{"year":2014,"num":115.5}
{"year":2016,"num":0.0}
{"year":2017,"num":8.28}
{"year":2018,"num":0.0}

我有一组颜色:

 let colors = ['#42d4f4','#e6194B','#3cb44b','#911eb4'];

我现在想将这些颜色添加到我的对象中。

我想让它看起来像这样:

{"year":2014,"num":115.5, "colors": '#42d4f4'}
{"year":2016,"num":0.0, "colors": '#e6194B'}
{"year":2017,"num":8.28, "colors": '#3cb44b'}
{"year":2018,"num":0.0, "colors": '#911eb4'}

有没有办法不用写很多if就可以做到这一点?

您可以使用新键color映射数组和return所有对象。

let data =[
  {"year":2014,"num":115.5},
  {"year":2016,"num":0.0},
  {"year":2017,"num":8.28},
  {"year":2018,"num":0.0}
];
let colors = ['#42d4f4','#e6194B','#3cb44b','#911eb4'];
let newData = colors.map((color, index) => ({...data[index], color}));
console.log(newData);

如果您不熟悉 ES6 语法,这与:

let data =[
  {"year":2014,"num":115.5},
  {"year":2016,"num":0.0},
  {"year":2017,"num":8.28},
  {"year":2018,"num":0.0}
];
let colors = ['#42d4f4', '#e6194B', '#3cb44b', '#911eb4'];
let newData = colors.map(function(colorHex, index) {
  return {
    year: data[index].year,
    num: data[index].num,
    color: colorHex
  }
})
console.log(newData) // [{"year":2014,"num":115.5, "colors": '#42d4f4'}, ...]

您可以使用map 遍历数组。使用扩展语法浅复制对象并使用索引添加 colors 属性。

let arr = [{
  "year": 2014,
  "num": 115.5
}, {
  "year": 2016,
  "num": 0.0
}, {
  "year": 2017,
  "num": 8.28
}, {
  "year": 2018,
  "num": 0.0
}];

let colors = ['#42d4f4', '#e6194B', '#3cb44b', '#911eb4'];

let result = arr.map((o, i) => ({ ...o, colors: colors[i] || null }));

console.log(result);


如果要更新现有变量,可以使用forEach

let arr = [{
  "year": 2014,
  "num": 115.5
}, {
  "year": 2016,
  "num": 0.0
}, {
  "year": 2017,
  "num": 8.28
}, {
  "year": 2018,
  "num": 0.0
}];

let colors = ['#42d4f4', '#e6194B', '#3cb44b', '#911eb4'];

arr.forEach((o, i) => o.colors = colors[i] || null);

console.log(arr);