如何更改数组的值并存储在新数组中?

时间:2019-08-09 17:39:01

标签: javascript arrays typescript

几个小时以来,我一直在搜索SO并尝试解决此问题: 我有一个对象数组。每个对象都有一个键/值对。我想更改某个键的值,并将其存储在新数组中。

请看看这个stackblitz

data:any[] = [
  { color: "brown", nr: 1},
  { color: "red", nr: 2},
  { color: "green", nr: 3}
]

newData: any[];

text() {
  const array = [];

  for (let i = 0; i < this.data.length; i++) {
    this.data['nr'] = i * 2;
    this.data['color'] = "yellow";
    array.push(this.data[i]);
    console.log(this.data[i]);
  }

  this.newData = array;
  console.log(array);
}

我希望newData数组具有新值,但不会成功。 显然我做错了。 有任何线索吗?

4 个答案:

答案 0 :(得分:2)

尝试使用.map函数:

let newArray = data.map((x, index) => ({
  color: 'yellow',
  nr: x.nr * index
}));

答案 1 :(得分:0)

this.data是一个数组。为了更改对象键值,请使用this.data[i][keyName]而不是this.data[keyName]

newData:any[] = []; // <-- Initiate to empty array

text (){
    const array = [];
    for (let i = 0; i < this.data.length; i++) {
        this.data[i]['nr'] = i*2;
        this.data[i]['color'] = "yellow";

        array.push(this.data[i]);
    }
    this.newData.push(...array);
    console.log(JSON.stringify(this.newData));
  }

答案 2 :(得分:0)

我认为一个关键问题是您是否打算突变原始数组-我认为其他答案正在更改原始数组的值,在这种情况下newData没有意义。同样正如randomSoul所指出的,您需要深入到数组的每个元素并从那里访问属性。

因此,假设您不打算对原始内容进行变异-这就是我将按照您的代码样式进行的操作:

data:any[] = [
  { color: "brown", nr: 1},
  { color: "red", nr: 2},
  { color: "green", nr: 3}
];

newData: any[];

text() {
  // There are better ways to deep copy but out of scope...
  // Need to create new reference if we do not want to mutate original
  const array = JSON.parse(JSON.stringify(this.data));

  for (let i = 0; i < array.length; i++) {
    array[i]['nr'] = i * 2;
    array[i]['color'] = "yellow";
  }

  this.newData = array;
}

答案 3 :(得分:0)

text (){
    const array = [...this.data]; // copy an array
    array.map((item, i) => {
      item["color"] = "yellow";
      item["nr"] = i * 2;
      console.log(item)
    })
    this.newData = [...array]; // copy an array
    console.log(this.newData);
  }