How to add index values of array in object to a key

Codenewbie :

I have an object in variable info as :

0: {ProId: "Space", Name: "cake", Quantity: 1}
1: {ProId: "new", Name: "walk", Quantity: 1}

I am trying to change the Quantity value to it's index+1 for each index ,

I have tried to have a static value as:

  for (var key in obj){
    var value= obj[key];
    value['Quantity'] = 5;
  }

Expected O/p:

console.log(info)
    0: {ProId: "Space", Name: "cake", Quantity: 1}
    1: {ProId: "new", Name: "walk", Quantity: 2}
    2: {............................Quantity: 3}.....

But May I know how can I have the Quantity value as above mentioned

Nina Scholz :

Some hints:

  • Take an array instad of an object, if you need an easy iterable data structure. This gives a control over the iteration order, too.
  • Use numbers for number values. If you need later a (formatted) string apply toString to it.

For getting a new value of a property, you could mutate the given data

Using:

var array = [{ ProId: "Space", Name: "cake", Quantity: "1" }, { ProId: "new", Name: "walk", Quantity: "1" }];

array.forEach((object, i) => object.Quantity = i + 1);

console.log(array);

Or get new objects by mapping the array.

Using:

var array = [{ ProId: "Space", Name: "cake", Quantity: "1" }, { ProId: "new", Name: "walk", Quantity: "1" }],
    newArray = array.map((object, i) => ({ ...object, Quantity: i + 1 }));

console.log(newArray);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11402&siteId=1