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:
Array#forEach
for vititing all items of the array,- an arrow function, a short form of a function.
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:
Array#map
for getting a new array,- spread syntax
...
for taking all properties of an object into a new object
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);