ArticleZip > Update If Exists Or Add New Element To Array Of Objects Elegant Way In Javascript Lodash

Update If Exists Or Add New Element To Array Of Objects Elegant Way In Javascript Lodash

Handling arrays of objects in JavaScript and updating elements within them can sometimes be a tricky task. However, with the help of a powerful library like Lodash, you can make this process more elegant and efficient. In this article, we will explore how to update an existing element in an array of objects or add a new element if it doesn't already exist using JavaScript and Lodash.

To begin with, let's consider a scenario where you have an array of objects representing items, and you want to update a specific item if it already exists in the array or add it as a new item if it doesn't.

First, make sure you have Lodash installed in your project. If you haven't already added it to your project, you can do so by running the following command:

Bash

npm install lodash

Once you have Lodash set up, you can start by importing it into your JavaScript file:

Javascript

const _ = require('lodash');

Next, let's define our array of objects. For this example, we'll create a simple array called `items`:

Javascript

let items = [
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Orange' }
];

Now, let's say we want to update the item with id `2` if it exists in the array, or add a new item with id `4` and name 'Grapes' if it doesn't. We can achieve this using Lodash's `findIndex` and `set` functions:

Javascript

const targetId = 2;
const targetItem = _.find(items, { id: targetId });

if (targetItem) {
    const index = _.findIndex(items, { id: targetId });
    _.set(items, `[${index}].name`, 'Updated Banana');
} else {
    items.push({ id: 4, name: 'Grapes' });
}

In this code snippet, we first use `_.find` to check if the item with id `2` exists in the `items` array. If it does, we retrieve its index using `_.findIndex` and update its name using `_.set`. If the item doesn't exist, we simply add a new item to the array.

By leveraging these simple yet effective Lodash functions, you can efficiently update existing elements in an array of objects or add new elements with ease. This not only streamlines your code but also makes your data manipulation logic more concise and readable.

So, next time you find yourself needing to update or add elements in an array of objects in JavaScript, consider using Lodash to simplify the process and make your code more elegant. Happy coding!

×