How to use find and assign Functions In Lodash
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'
}
]
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.
Table of Content
- Using find and assign Functions
- Using findIndex Function
Run the below command to install Lodash:
npm i lodash