2

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212
  • 1
    I removed the "best" from your title and text because I'm guessing you're look for "a way" rather than some opinionated "best" way, which would be off topic for SO. – Heretic Monkey May 18 '16 at 18:09

3 Answers3

5

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

tymeJV
  • 103,943
  • 14
  • 161
  • 157
4

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}) );
qwertymk
  • 34,200
  • 28
  • 121
  • 184
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;
});

Implementations of clone

Community
  • 1
  • 1
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104