Jojoseph
Jojoseph

Reputation: 119

How to change values of an array and store in new array?

For several hours I've been searching on SO and trying to solve this: I have an array with objects. Each object has a key/value pair. I want to change the values of a certain key and store this in a new array.

Please have a look at this 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);
}

I expect the newData array would have the new values, but no success. Obviously I am doing something wrong. Has anyone a clue?

Upvotes: 0

Views: 1051

Answers (4)

Islam
Islam

Reputation: 3

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

Upvotes: 0

MrRobboto
MrRobboto

Reputation: 752

A key question I think would be if you plan to mutate the original array or not - other answers I believe are changing the values of the original array and there's no point in newData in that case. Also as randomSoul pointed out, you need to drill into each element of the array and access properties from there.

So assuming you are not trying to mutate the original - this is what I would do following your code style:

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

Upvotes: 0

cullanrocks
cullanrocks

Reputation: 497

Try using the .map function:

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

Upvotes: 2

random
random

Reputation: 7891

this.data is an array. In order to change the object key values, use this.data[i][keyName] instead of 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));
  }

Upvotes: 0

Related Questions