0

First array

userData = [
    { name: abc, age: 24 },
    { name: ghi, age: 22 },
    { name: tyu, age: 20 }
];

Second array

userAge = [
    { age: 25 },
    { age: 26 },
    { age: 22 }
];

Both arrays have the same length.

How do I update the useData[0].age with userAge[0] using Underscore.js?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Debashrita
  • 940
  • 1
  • 8
  • 20
  • If you are satisfied with one of the answers, please accept it. You could also add your own answer if the existing one is incomplete / incorrect @Debashrita – martianwars Dec 28 '16 at 08:01

2 Answers2

0

Since you need to do this over a list of dictionaries, you will need to iterate over the list using _.each.

Something like this will help,

_.each(userData, function(data, index) {
    data.age = userAge[index].age;
}); 
martianwars
  • 6,380
  • 5
  • 35
  • 44
0

While @martianwars is correct, it could be a little more generic, thus more useful, if it could apply any attribute.

Say we have an array of changes to apply, with each not being necessarily the same attribute or even multiple attributes per object:

var changes = [
    { age: 25 },
    { name: "Guy" },
    { name: "Pierre", age: 22 }
];

Changes could be applied with _.extendOwn

_.each(userData, function(data, index) {
    _.extendOwn(data, changes[index]);
});

Proof of concept:

var userData = [{
  name: "abc",
  age: 24
}, {
  name: "ghi",
  age: 22
}, {
  name: "tyu",
  age: 20
}];

var changes = [{
  age: 25
}, {
  name: "Guy"
}, {
  name: "Pierre",
  age: 22
}];


_.each(userData, function(data, index) {
  _.extendOwn(data, changes[index]);
});

console.log(userData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

This will only work if the arrays are in sync. Meaning that if there are 4 objects in the userData array, and only 3 changes, they need to be at the right index and that could become a problem.

A solution to this is to have an identification property, often represented by an id attribute.

userData = [
    { id: '1', name: 'abc', age: 24 },
    { id: '2', name: 'ghi', age: 22 },
    { id: '3', name: 'tyu', age: 20 }
];

See Merge 2 objects based on 1 field using Underscore.js for details.

Community
  • 1
  • 1
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129