Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this:

arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]
. However, I need to add a condition to the array. If the id 'fifth' is found in the array, then I want to update it to look like this:

arr = [{id:'first',name:'John'},{id:'sixth',name:'Kat'},{id:'eitghth',name:'Isa'}]

I only need to modify one part of an item. How can I achieve this using JavaScript?

Answer №1

To locate the entry and update its id attribute, you can utilize the Array.prototype.find method:

const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa']];

const entry = arr.find(item => item.id === 'fifth');
entry.id = 'sixth';

console.log(arr);

If you want to replace a specific entry by finding its index, you can also make use of Array.prototype.findIndex:

const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa']];

const targetIndex = arr.findIndex(item => item.id === 'fifth');
arr[targetIndex].id = 'sixth';

console.log(arr);


If there are multiple entries with the same ID in the array and you need to update all of them, iterating through the array is a better approach:

const arr = [{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'}];

arr.forEach(item => {
  if (item.id === 'fifth') {
    item.id = 'sixth';
  }
});

console.log(arr);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting an array of objects into a flat array of objects with Javascript

My data array requires conversion to a flattened array returning new header and data. For instance, the first object contains a name with three data points: "title, first, last." The desired output is: From : { gender: 'male', name: { ...

Set the current time to ISO8601 format

I need assistance with creating a "time passed" counter for my website based on an API call that returns data in the following format: "created_at": "2018-05-16T14:00:00Z", What is the best approach to calculate and display the time that has passed since ...

Having trouble with integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...

Are the functionalities of twilio-common.js on github equivalent to those of twilio-client.js on their CDN?

Currently, I am integrating the Twilio SDK client from the twilio CDN using this link: //media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js However, I am interested in importing the package via npm due to some restrictions. The only option I see availa ...

Expand and enhance your content with the Vue Sidebar Menu plugin

Recently, I integrated a side-bar-menu utilizing . My goal is to have a sidebar menu that pushes its content when it expands. Any suggestions on which props or styles I should incorporate to achieve this effect? Below is my Vue code: <template> ...

The some() method in Javascript with an extra argument

I want to validate if at least one element in an array satisfies a certain condition. The condition is based on a variable. Here's an example of how I'm currently attempting this: function checkCondition(previousValue, index, array) { retur ...

An Unexpected Token Leads to a SyntaxError in Jest's CSS-Modules

I have successfully configured my jest to allow the usage of static files by following their detailed documentation. However, despite implementing the instructions correctly, I am still encountering an error: What steps can I take to resolve this issue an ...

Exploring AngularJS $compile and the concept of scoping within JavaScript windows

I've encountered a scoping issue with the use of this inside an angular-ui bootstrap modal. The code below functions perfectly outside of a modal, but encounters problems when run within one: var GlobalVariable = GlobalVariable || {}; (fun ...

When utilizing the .populate() method in Mongoose, how can you retrieve and append ObjectIds with extra attributes to an array (which is returned by .populate()) collected from the

When using the .populate() method in Mongoose, how can I retrieve and add ObjectIds with additional properties to an array (returned by .populate()) if their corresponding document in the collection no longer exists? This question pertains to MongoDB and ...

Calculating the total sum of data in a JSON file by grouping it based

I have an online JSON file with the following information: {'skladiste': 1, 'sifra': '7138', 'nc': 0.8, 'vpc': 47.01, 'mpc': 55.0, 'stanje': 5.0, 'aktivan': 255, 'lokacija ...

What is the best way to send multiple id values with the same classname as an array to the database via AJAX in Codeigniter?

Hey everyone, I'm facing an issue where I need to send multiple IDs with the same class name but different ID values to the database using AJAX. However, when I try to do this, only the first value is being picked up and not all of them. How can I suc ...

What are the reasons behind Jquery's decreased speed performance in Internet Explorer?

My ASP.NET page is quite intricate and heavily depends on jQuery for manipulating the DOM without using AJAX. Interestingly, I've observed that the page performs better in Mozilla browsers like Firefox compared to Internet Explorer 7 or 8. Could it b ...

The radial gradient in d3.js does not properly affect paths

My goal is to create a radial gradient on my path element, but for some reason the radial gradient does not apply correctly. Can anyone help me troubleshoot this issue? Below is my updated code: // Define the canvas / graph dimensions var margin = {top: ...

Showcase pictures from a directory in real-time using a combination of jQuery and Bootstrap as the folder continues to fill up with images

Although I am just beginning to learn about UI, I have a question that seems important to me. In my application, there is a background thread that downloads images and saves them in a folder named "images". I want these images to be displayed in the UI as ...

Using AJAX to remove data from a database

My PHP code snippet is displayed below: AjaxServer.php include '../include/connection.php'; // Check for the prediction if(isset($_POST["delete_me"]) && $_POST["delete_me"]=="true"){ $id = $_POST["id"]; $table = $_POST["table"]; ...

SVGs do not display on iPhones

Having some issues with my code - specifically, I have an SVG animation that seems to work on all devices except iPhones. I've been struggling to find a solution. Here is the code snippet for the SVG: <div class="contenuto-svg"> <svg vi ...

I am looking to split an array into smaller subarrays, each containing 5 elements, and assign a distinct class to the elements within each subarray. How can I

I have a group of "n" "li" elements that I would like to split into "x" subsets using jQuery. Each subset should contain 5 "li" elements, and I also want to assign a different class to each subset. <ul> <li>text1</li> <li>text2&l ...

Ways to switch out error message for an error landing page

I am currently displaying error text when something goes wrong, but I would like to enhance the user experience by redirecting to a well-designed error page instead. Can anyone provide guidance on how to achieve this? Below is my existing code for display ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...