简体   繁体   中英

Javascript Object array sum in specific object position

I have this array:

let arr = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, 
            { "Id": 0, "Name": "Product 1", "Price": 15 } ]

How can i sum 1 in all Price positions to be like:

let Final_arr = [ { "Id": 0, "Name": "Product 1", "Price": 11 }, 
                  { "Id": 0, "Name": "Product 1", "Price": 16 } ]

Thanks! ;)

loop through the array and increment the price : keep in mind that this will mutate the original array, use arr.slice(0).forEach( ... to keep the original as is.

 let arr = [{ "Id": 0, "Name": "Product 1", "Price": 10 }, { "Id": 0, "Name": "Product 1", "Price": 15 } ] arr.forEach((e) => { return e.Price++ }); /* const newArr = arr.slice(0).forEach((e) => { return e.Price++ }); */ console.log(arr) 

You could also use a for loop:

 var arr = [{ "Id": 0, "Name": "Product 1", "Price": 10 }, { "Id": 0, "Name": "Product 1", "Price": 15 } ]; for (var i = 0; i < arr.length; i++) arr[i].Price++; console.log(arr); 

arr.map((a) => { a.Price = a.Price + 1 });

You can clone the array and map it to get a new one, like this:

 let arr = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, { "Id": 0, "Name": "Product 1", "Price": 15 } ]; let newArr = JSON.parse(JSON.stringify(arr)).map(function(item){ item.Price++; return item; }); console.log(newArr); 

Using es2015 syntax this could be achieved with:

const Final_arr = arr.map((item) => {
    return { ...item, price: item.Price + 1 };
});

Using vanilla JS, you could do like below:

var Final_arr = arr.map(function (item) {
    return { Id: item.Id, Name: item.Name, Price: item.Price + 1 };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM