johowie
johowie

Reputation: 2495

mix object properties into an array of objects

What is the most efficient way to mix in the values from extra into arr, to produce result without modifying arr in any way? using: plain javascript, underscore, lodash(underscore compat), jquery OR lodash, in order of preference.

arr = [
  {name: "A"},
  {name: "B"},
  {name: "C"},
]

.

extra = {
  "B": value1
  "C": value2
}

.

result == [
  {name: "A"},
  {name: "B", extra: value1},
  {name: "C", extra: value2},
] 
// true !

Upvotes: 1

Views: 430

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191779

for (var x = 0; x < arr.length; x++) {
    if (arr[x].hasOwnProperty('name')) {
       if (extra.hasOwnProperty(arr[x].name)) {
           arr[x].extra = extra[arr[x].name];
       }
    }
}

The outer hasOwnProperty is probably overkill.

http://jsfiddle.net/Y3Abe/2/

Upvotes: 2

Related Questions