How to Find & Update Values in an Array of Objects using Lodash ?
Last Updated :
18 Jul, 2024
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.
JavaScript
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.
JavaScript
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 }
]
Using map Function
In this approach, we use the _.map function from Lodash to iterate over the array of objects and create a new array with updated values based on a specified condition. This approach is useful for making updates and returning a new array without mutating the original array.
Example: The below example uses map to find and update values in an array of objects using lodash.
JavaScript
const _ = require('lodash');
let employees = [{
id: 1,
name: 'Nikunj',
salary: 5000
},
{
id: 2,
name: 'Dhruv',
salary: 6000
},
{
id: 3,
name: 'Yash',
salary: 7000
}
];
let updatedEmployees = _.map(employees, (employee) => {
if (employee.id === 2) {
return _.assign({}, employee, { salary: 6500 });
}
return employee;
});
console.log(updatedEmployees);
Output:
[
{ id: 1, name: 'Nikunj', salary: 5000 },
{ id: 2, name: 'Dhruv', salary: 6500 },
{ id: 3, name: 'Yash', salary: 7000 }
]
Using forEach Function
In this approach, we use the _.forEach function from Lodash to iterate over the array of objects and directly update the values in the original array based on a specified condition. This approach is useful for in-place updates.
Example:
JavaScript
const _ = require('lodash');
let products = [
{ id: 1, name: 'Laptop', price: 1000 },
{ id: 2, name: 'Phone', price: 500 },
{ id: 3, name: 'Tablet', price: 300 }
];
_.forEach(products, (product) => {
if (product.id === 2) {
product.price = 550;
}
});
console.log(products);
Output:
[
{ id: 1, name: 'Laptop', price: 1000 },
{ id: 2, name: 'Phone', price: 550 },
{ id: 3, name: 'Tablet', price: 300 }
]
Similar Reads
How to use Lodash to Find & Return an Object from Array ?
JavaScript's built-in array methods offer basic functionality whereas Lodash, a popular utility library, empowers developers with robust tools for complex array operations. Below are the methods to find and return an object from array using Lodash: Table of Content Using _.find()Using _.findIndex()
3 min read
How to use Lodash to find & Return an Object from Array ?
In JavaScript, the Lodash Module has different methods of doing and get objects from the array. we will explore three different methods with practical implementation of each approach in terms of examples and output to to find and return an object from Array. These are the following methods: Table of
3 min read
How to Replace Objects in Array using Lodash?
Replacing objects in an array using Lodash typically involves identifying the specific object(s) you want to replace and then performing the replacement operation. Lodash provides a range of methods to facilitate such operations, although the actual replacement might involve combining Lodash functio
3 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to updating an array of objects with another array of objects in the Lodash library:Table of ContentUsing loda
4 min read
How To Update An "array of objects" With Firestore?
Firestore, a NoSQL database from Firebase, is widely used for building real-time, scalable web and mobile applications. One of the common tasks while working with Firestore is updating documents, particularly when working with complex data structures like arrays of objects.In this article, we will w
6 min read
How to Update MongoDB Field Using Value of Another Field
In the NoSQL database, MongoDB is the most robust and flexible option for managing big data. One common problem that occurs when working with MongoDB is to Update the MongoDB field using the value of another field and change data within our database.In this article, we will learn about How to Update
3 min read
How to Filter Key of an Object using Lodash?
Filtering keys of an object involves selecting specific keys and creating a new object that contains only those keys. Using Lodash, this process allows you to include or exclude properties based on specific criteria, simplifying object manipulation. Below are the approaches to filter keys of an obje
2 min read
How to Update the First Object in an Array in MongoDB
MongoDB, a popular NoSQL database, offers powerful features for handling complex data structures. One common scenario is updating specific elements within arrays stored in documents. In this guide, we'll focus on updating the first object in an array within a MongoDB document. We'll cover the concep
3 min read
How to Find Property Values in an Array of Object using if/else Condition in JavaScript ?
Finding property values in an array of objects using if/else condition is particularly useful when there is a collection of objects. Table of ContentUsing Array Find MethodUsing Array Filter MethodUsing For Of LoopUsing Array Map MethodUsing Array Reduce MethodUsing Array Some MethodUsing Array Find
5 min read
How to Filter Object by Keys or Values in Lodash?
Filtering objects is a common requirement when we want to extract certain data from larger datasets. Lodash provides convenient methods to do this, which helps us in avoid writing complex loops and conditional statements. Below are different approaches to filter objects by keys or values in lodash:T
3 min read