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
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg. We see above that we can loop a numerical array using the jQuery.
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
...
), 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)
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.
.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.
Yes.
[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
.map()
methodYou 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).
Sure you can.
const arr = [{value: 1}, {value: 1}, {value: 2}] const newArr = arr.map(addIsActive) function addIsActive(v) { return {...v, isActive: true} }
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 }
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With