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?

1
  • 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 Commented Dec 28, 2016 at 8:01

2 Answers 2

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;
}); 
Sign up to request clarification or add additional context in comments.

3 Comments

To just update one element, why do you need underscore.js? You can just do userData[0].age = userAge[0].age right?
not one element i gave an exapmle . we need to update userData[i].age = userAge[i].age
As you're mutating userData you might as well use _.each rather than _.map
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.