Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 array of objects:

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

I want to add another property to each of the objects in the array and want the value to be 25 less the previous one.

So what I want my object to look like (expected result):

arr_obj = [
   {
     name: 'Hermione',
     order: 'books',
     order_size: 100,
   },
   {
     name: 'Harry',
     order: 'brooms',
     order_size: 75, //100-25  
   },
   {
     name: 'Ron',
     order: 'food',
     order_size: 50, //75-25   
   }
]

I tried a forEach but that is not working. It does not subtract the 25.

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

When I do this, I am getting:

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

How do I get the expected result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...