Open In App

How to Find & Update Values in an Array of Objects using Lodash ?

To find and update values in an array of objects using Lodash, we employ utility functions like find or findIndex to iterate over the elements. These functions facilitate targeted updates based on specific conditions, enhancing data manipulation capabilities.

Run the below command to install Lodash:

npm i lodash

Using find and assign Functions

In this approach, we are using Lodash's find function to locate the object with an id equal to 102 in the courses array. Then, we use the assign method to update its duration property to '10 weeks', demonstrating a targeted find-and-update operation in an array of objects using Lodash.

Example: The below example uses find and assign functions to find and update values in an array of objects using lodash.

const _ = require('lodash');
let courses = [{
    id: 101,
    name: 'Programming with Python',
    duration: '4 weeks'
},
{
    id: 102,
    name: 'Data Structures and Algorithms',
    duration: '6 weeks'
},
{
    id: 103,
    name: 'Web Development with JavaScript',
    duration: '8 weeks'
}
];
let courseToUpdate = _.find(courses, {
    id: 102
});
if (courseToUpdate) {
    _.assign(courseToUpdate, {
        duration: '10 weeks'
    });
}
console.log(courses);

Output:

[     
{ id: 101, name: 'Programming with Python', duration: '4 weeks' },
{
id: 102,
name: 'Data Structures and Algorithms',
duration: '10 weeks'
},
{
id: 103,
name: 'Web Development with JavaScript',
duration: '8 weeks'
}
]

Using findIndex Function

In this approach, we use _.findIndex to locate the index of the object with an id equal to 3 in the student's array. Then, we update the score property of that object to 80 if the index is found, demonstrating a targeted find-and-update operation using Lodash's findIndex function.

Example: The below example uses findIndex to find and update values in an array of objects using lodash.

const _ = require('lodash');
let students = [{
    id: 1,
    name: 'Gaurav',
    score: 85
},
{
    id: 2,
    name: 'Ramesh',
    score: 92
},
{
    id: 3,
    name: 'Prakash',
    score: 78
}
];
let indexToUpdate = _.findIndex(students, {
    id: 3
});
if (indexToUpdate !== -1) {
    students[indexToUpdate].score = 80;
}
console.log(students);

Output:

[
{ id: 1, name: 'Gaurav', score: 85 },
{ id: 2, name: 'Ramesh', score: 92 },
{ id: 3, name: 'Prakash', score: 80 }
]
Article Tags :