简体   繁体   中英

How to add key value pair to objects in an array?

I am supposed to add a new key value pair of 'family: true' to each object. I am also supposed to use the forEach method. My code adds 'family: true' to the end of the array but I don't think that's what I am meant to do.

Here is the array:

var goodPeople = [{name: 'George'}, {name: 'Randi'}, {name: 'Lindsey'}]

My code:

goodPeople.forEach(function(){
  goodPeople.push({family:true});
});

You need to learn how to use forEach - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

goodPeople.forEach(function(item){
    item.family = true;
});

in each iteration, item is one of the objects in the Array

there, you can add a key/value pair as you call it to each item in the Array , one at a time

Loop through the elements of the array which are objects, then assign the property to each.

goodPeople.forEach(function(element){
 element.family = true;
});

You can use forEach or map depending if you want to mutate the original array.

With ForEach and ES6:

goodPeople.forEach(i => { i.family = true });

If you don't want to mutate the original array you can use map:

var familyGoodPeople = goodPeople.map(i => Object.assign({}, i, {family: true }))

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