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
Some hints:
toString
to it.For getting a new value of a property, you could mutate the given data.
Using:
Array#forEach
for visiting all items of the array,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,...
for taking all properties of an object into a new objectvar 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);
You can map the array and return a new array but merging the old object with new object with updated Quantity
value like:
const data = [{ProId: "Space", Name: "cake", Quantity: "1"}, {ProId: "new", Name: "walk", Quantity: "1"}],
updatedData = data.map((x, i)=> ({...x, Quantity: ++i}));
console.log(updatedData)
.as-console-wrapper { max-height: 100% !important; top: 0; }
A simple example of updating an object key value (which is done here inside the map()
method) is like:
let obj = { a: 0, b: 0};
let newObj = { ...obj, a: 1 };
console.log( newObj )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With