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

Categories

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

javascript - Add key value pair to all objects in array

I wanted to add a key:value parameter to all the objects in an array.

eg:

var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];

Now I wanted to add a new parameter, isActive to all the objects so the resulting array will look like.

eg:

    [{
    name: 'eve',
    isActive: true
}, {
    name: 'john',
    isActive: true
}, {
    name: 'jane',
    isActive: true
}]

I can always loop through the array and insert a key,value pair. But was wondering if there was a better way to do so

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can do this with map()

var arrOfObj = [{
  name: 'eve'
}, {
  name: 'john'
}, {
  name: 'jane'
}];

var result = arrOfObj.map(function(o) {
  o.isActive = true;
  return o;
})

console.log(result)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...