Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

javascript - 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 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

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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...