将键值对添加到数组中的所有对象

我想为数组中的所有对象添加一个 key: value 参数。

例如:

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

现在我想为所有对象添加一个新参数 isActive,这样生成的数组看起来就像。

例如:

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

我总是可以循环遍历数组,并插入一个键,值对。但我想知道有没有更好的办法

213593 次浏览

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)

If you want to keep original array you can clone objects with Object.assign()

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


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


console.log(arrOfObj);
console.log(result);

The map() function is a best choice for this case


tl;dr - Do this:

const newArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
].map(v => ({...v, isActive: true}))

The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.


Alternatives:

const initialArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
]


const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))


// Results of newArr1 and newArr2 are the same

Add a key value pair conditionally

const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))

What if I don't want to add new field at all if the condition is false?

const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(v => {
return v.value > 1 ? {...v, isActive: true} : v
})

Adding WITH modification of the initial array

const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});

This is probably not a best idea, but in a real life sometimes it's the only way.


Questions

  • Should I use a spread operator(...), or Object.assign and what's the difference?

Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)

  • Can I use function keyword instead of =>?

Sure you can. The fat arrow (=>) functions play a bit different with this, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.

  • What Actually happens inside map function: .map(v => ({...v, isActive: true})?

Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array. We tell to the .map() function following: take current value(v which is an object), take all key-value pairs away from v andput it inside a new object({...v}), but also add property isActive and set it to true ({...v, isActive: true}) and then return the result. Btw, if original object contains isActive filed it will be overwritten. Object.assign works in a similar way.

  • Can I add more then one field at a time

Yes.

[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
  • What I should not do inside .map() method

You shouldn't do any side effects[link 1, link 2], but apparently you can.

Also be noticed that map() iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).

  • Can I extract map's callback to a separate function?

Sure you can.

const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(addIsActive)


function addIsActive(v) {
return {...v, isActive: true}
}
  • What's wrong with old good for loop?

Nothing is wrong with for, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:

const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
arr[i].isActive = true
}
  • What also i should learn

It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.

Looping through the array and inserting a key, value pair is about your best solution. You could use the 'map' function but it is just a matter of preference.

var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
arrOfObj.map(function (obj) {
obj.isActive = true;
});

Simply use map function:

var arrOfObj = arrOfObj.map(function(element){
element.active = true;
return element;
}

Map is pretty decent on compatibility: you can be reasonably safe from IE <= 9.

However, if you are 100% sure your users will use ES6 Compatible browser, you can shorten that function with arrow functions, as @Sergey Panfilov has suggested.

You may also try this:

arrOfObj.forEach(function(item){item.isActive = true;});


console.log(arrOfObj);

@Redu's solution is a good solution

arrOfObj.map(o => o.isActive = true;) but Array.map still counts as looping through all items.

if you absolutely don't want to have any looping here's a dirty hack :

Object.defineProperty(Object.prototype, "isActive",{
value: true,
writable: true,
configurable: true,
enumerable: true
});

my advice is not to use it carefully though, it will patch absolutely all javascript Objects (Date, Array, Number, String or any other that inherit Object ) which is really bad practice...

    var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
var injectObj = {isActive:true, timestamp:new Date()};


// function to inject key values in all object of json array


function injectKeyValueInArray (array, keyValues){
return new Promise((resolve, reject) => {
if (!array.length)
return resolve(array);


array.forEach((object) => {
for (let key in keyValues) {
object[key] = keyValues[key]
}
});
resolve(array);
})
};


//call function to inject json key value in all array object
injectKeyValueInArray(arrOfObj,injectObj).then((newArrOfObj)=>{
console.log(newArrOfObj);
});

Output like this:-

[ { name: 'eve',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'john',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z },
{ name: 'jane',
isActive: true,
timestamp: 2017-12-16T16:03:53.083Z } ]

I would be a little cautious with some of the answers presented in here, the following examples outputs differently according with the approach:

const list = [ { a : 'a', b : 'b' } , { a : 'a2' , b : 'b2' }]


console.log(list.map(item => item.c = 'c'))
// [ 'c', 'c' ]


console.log(list.map(item => {item.c = 'c'; return item;}))
// [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]


console.log(list.map(item => Object.assign({}, item, { c : 'c'})))
// [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]

I have used node v8.10.0 to test the above pieces of code.

arrOfObj.map(o => {
o.isActive = true;
return o;
});
_.forEach(arrOfObj,(arrVal,arrIn) => {
arrVal.isAcitve = true;
}
let arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
let newArr = arrOfObj.map(i => ({...i,isActive: true}));

Here what i did was i spread the current object and insert a new key with a value to the object and return it as a new object.

var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
const result = arrOfObj.map((name) => {
name["isActive"] = true;
return name;
});
console.log(result);