简体   繁体   中英

Append property to each object within array

Good morning all,

So here I asked myself the question to see if I was optimizing this rating there but I feel like I'm doing the wrong thing.

So let me explain.

We recover an array with objects, example of users.

Who would give this:

 [
   {
     'name': 'john',
     'age': '25'
   },
   {
     'name': 'Doe',
     'age': '28'
   },
   ...
 ]

But in vuejs or in javascript or other, I find myself sometimes adding an example value: "'edit': false", but here to add it to all my objects in my table I pass the table with an each and i add this value like that. but I don't find it clean would you have another tip or just how do you do it?

 [
   {
     'name': 'john',
     'age': '25',
     'edit': false
   },
   {
     'name': 'Doe',
     'age': '28',
     'edit': false
   },
   ...
 ]

i do like that personally

$.each(this.users, function(key){
                        Vue.set(this, 'edit', false)
                    });

Thank you for your answers I wish you a good day and above all good health. Sorry about my bad english!

If you use ES6, you can do one liner like that:

var users = [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 28 }
];

users.map(user => user.edit = false);

Use map and spread operator

const users = [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 28 }
];

const usersUpdated = users.map(user => ({ ...user, edit: false }));

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