Is there a way to add the same item val="4" to each object of array in JavaScript?
Let's say there is
var arr = [{"num":"111"},{"ttt":"123","rss":"456"},...];
I'd like to get
arr2 = [{"num":"111", "val":"4"},{"ttt":"123", "rss":"456", "val":"4"},...];
Is it possible to make in one line with kind of .push()
to array or something similar?
The .map
function will work wonders for you!
var arr2 = arr.map(function(item) {
item.val = 4;
return item;
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
While tymeJV's solution works, I find it slightly confusing as .map()
is meant to return new objects and .forEach()
is meant for doing side effects.
If you wanted to mutate the original array then this makes more sense IMO
arr.forEach(function(item) {
item.val = 4;
})
If you wanted to return a new array and leave the old one untouched then this should work
var arr2 = arr.map(function(item) {
return Object.assign({}, item, {val: 4})
})
Or if you're targeting a browser that allows arrow functions:
var arr2 = arr.map(item => Object.assign({}, item, {val: 4}) );
(Very similar to @tymeJV)
You could actually use .forEach(..)
instead of .map
. You could technically do the achieve the same thing with both but there is a subtle stylistic (cross-language) difference. Use map
when you are literally converting each object from one form to another without modifying the original object . If you want to modify the original object, you'd typically use forEach
instead.
//Makes changes in place (original array is modified.
arr.forEach(function(item) {
item.val = 4;
});
//To ensure the original object `arr` isn't modified
arr2 = arr.map(function(item) {
var cloneObj = clone(item); //For clone see link below
cloneObj.val = 4;
return cloneObj;
});
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.