0

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?

3
  • What is the expected result? Commented Aug 9, 2019 at 17:41
  • 2
    Hint: this.data is an array...it has no properties nr or color...it's elements do Commented Aug 9, 2019 at 17:41
  • @L.Yogev why would that be a problem? Commented Aug 9, 2019 at 17:47

4 Answers 4

2

Try using the .map function:

let newArray = data.map((x, index) => ({
  color: 'yellow',
  nr: x.nr * index
}));
Sign up to request clarification or add additional context in comments.

1 Comment

This is for me the best solution: Nice and short. The other solutions (@MrRobboto, @randomSoul, @Islam) worked as well, with or without changing the original Array. Great! I Updated the stackblitz with the different solutions.
0

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

Comments

0

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

1 Comment

Side note - TypeScript can really help you here if you type your data object, i.e.,: data: {color:string, nr: number}[] Then to access in your loop you could actually just do data[i].nr, data[i].color and if you change the types you'll get compile-time errors.
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);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.