Skip to content Skip to sidebar Skip to footer

Add Key And Incremental Values To Array Of Objects

I have an array of objects. I want to add another property to each of the objects but I want the value to be incremental in nature. I want each to be 5 more than the other. My arra

Solution 1:

You forgot to modify order_size on each iteration. try this:

let arr_obj = [
       {
         name: 'Hermione',
         order: 'books',
       },
       {
         name: 'Harry',
         order: 'brooms',
       },
       {
        name: 'Ron',
        order: 'food',
       }
    ];

let order_size = 100;
arr_obj.forEach(d => {
   d['order_size'] = order_size;
   order_size -= 25;
});
console.log(arr_obj)

Solution 2:

The forEach method will also give you a key (numeric value that increments by one for each item) you can use this to do any necessary incrementing or decrementing of values in an array.

for example if you want a value that increases by 5 each time

arr_obj.forEach( (item, key) => {
  item.newValue = key*5
});

or if you want to reduce a value by 25 each time:

arr_obj.forEach( (item, key) => {
  item.order_size = 100 - (key*25)
});

This is possibly better practice than updating any variable outside of the current function

Post a Comment for "Add Key And Incremental Values To Array Of Objects"