Changing the value of a property in an object based on the object's attribute in JavaScript

I have a JSON data set like this:

inputData = [
{ id : 179849, name : alex , lastname: sanchez},
{ id : 788539, name : Paul, lastname: bearer},
{ id : 282169, name : Jean, lastname: nobel},
...
{ id : 632785, name : Maria, lastname: parak}
]

I am looking to find an object based on its id value (for instance: 788539 )

and then change the value of its name attribute -> name becomes : bruno

The updated data would look like this:

resultData= [
{ id : 179849, name : alex , lastname: sanchez},
{ id : 788539, name : bruno, lastname: bearer},  /* UPDATED ENTRY*/
{ id : 282169, name : Jean, lastname: nobel},
...
{ id : 632785, name : Maria, lastname: parak}
]

What is the easiest way to filter / map my data in order to make this modification?

Answer №1

responseData= [
{ id : 179846, name : John , lastname: Doe},
{ id : 788531, name : Emily, lastname: Smith},  /* CHANGED HERE*/
{ id : 282163, name : Michael, lastname: Brown},
...
{ id : 632781, name : Sophia, lastname: Johnson}
];

id = 788531;

responseData.forEach(element=>{
    if(element.id == id){
    element.name = 'Emily'
    }
});

console.log(responseData);

Answer №2

If you're looking for some alternatives, one suggestion made by Felix Kling may require a polyfill:

// Suggested by Felix Kling 
inputData.find(x => x.id === 788539)
  .name = 'Bruno'

Another option is to utilize the for of loop:

for (let item of inputData) {
  if (item.id === 788539) {
    item.name = 'Bruno'
    break
  }
}

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

Analyzing the string's worth against the user's input

I need help figuring out how to save user input on a form (email and password) as variables when they click "Register", so that the data can be used later if they choose to click "Login" without using default information. I am working on this project for s ...

How can I retrieve the selected items from a Listbox control?

Currently, I am working on an ASP.NET application using C#. One of the features in my project involves a Grid View with a Listbox control. The Listbox is initially set to be disabled by default. My goal is to enable and disable this control dynamically bas ...

Server nearby designated to handle requests to the api

Currently, I am working on a project involving automation. Within Adobe CEP, there is a local server that operates on Node.js/Express. My goal is to send an API request from a cloud server to this local server. How can I establish a connection between my l ...

Is it possible to modify the location of my CSG object prior to performing subtraction in Threejs with ThreeCSG?

Looking to carve out specific "voids" in platforms using ThreeCSG. The goal is to have these voids positioned at particular locations on the larger platform. var geometry = new THREE.CubeGeometry( 500, 10, 500 ); var hole_geometry = new THREE.CubeGeom ...

bxSlider adds in an empty slide after deleting an image

Whenever I click a link in my navigation, I want to remove certain images from the page. I tried implementing a solution, but now I have two empty spaces where the images used to be. How can I remove those as well? I searched on Stack Overflow for a soluti ...

jQuery ceases to function once AJAX content is loaded

Exploring Options for Flexible Data Display I'm currently in the process of building a webpage that allows users to choose between different layouts for loading data. This includes the option to display data in either a list format or a card interfac ...

Eliminate the usage of JSON.stringify in the Reducer function

I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed. Is there a way to enhance the existing code to eliminate the ...

What is the best way to simulate a service that returns a promise when writing unit tests for AngularJS using Jasmine?

I have a service named myService that relies on another service called myOtherService. The latter makes a remote call and returns a promise. Here's the implementation: angular.module('app.myService', ['app.myOtherService']) .fac ...

Dealing with request-specific or session-specific data in LoopBack 4

I am currently facing a challenge within our LoopBack4 application. We have implemented controllers and are using JWT for Authorization. In the token's payload, we include a list of rights granted to the requesting user. Additionally, we have added an ...

Pulling JSON Data with Ajax Request

I am attempting to retrieve the following JSON Data: {"status":"success","id":8,"title":"Test","content":"This is test 12"} Using this Ajax Request: $.ajax({ url: 'http://www.XXX.de/?apikey=XXX&search=test', type: "GET", dataType: 'js ...

Node.js is great at hosting HTML files, but struggles when it comes to loading script files within those pages

Recently, I’ve been working on creating a simple login page using a mongoDB database along with Node.js and express. Since I'm still new to Node.js, I'm facing an issue that seems more complicated than it actually is. The main problem I’m en ...

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

What is the best method for retrieving an array stored within a Json object?

Upon receiving a JSON response, my goal is to extract all project names listed within. After trying the usual method of iterating through arrays, I realized that in this case, "d" is not an array itself. How can I go about retrieving the desired result? ...

Combining Typescript and React to create a conditional callback prop type depending on whether an optional prop is

In my react component, I have the option to pass an optional prop called isSingle (boolean) and a required prop called onSelect (callback). If the isSingle prop is used, I want the callback to have a different signature. type CustomProps<T> = { ...

Calculate the product of a JavaScript variable and a PHP variable, then show the result on the

I need to calculate the product of a PHP variable value and a JavaScript variable, then show the result on the screen. Here is my PHP code: <?php require 'config.php'; session_start(); ?> <html> <head> < ...

When trying to access an array directly within an object, it all too often returns as undefined

There is a React Component that has been provided with an array of objects (main_object), one of which contains another array of objects (secondary_object). Strangely, when trying to print the main object in console.log, the array is visible, but attemptin ...

The ng-model remains empty even after the $parent has been defined

I've encountered an issue where assigning ng-model to a text area and an input does not update the models. It is mentioned that this could be due to using ng-if causing a different scope, and I should use $parent, but even that solution is not working ...

Display or conceal a div based on the size of the screen using HTML and CSS

Hey there, I recently finished my first React Project and I’m wondering if there’s a way to hide the 'side-menu' section on mobile screens using CSS. Any suggestions? <div className='side-menu'> <SiderComponent /> < ...

Dealing with CORS, IIS7, and PHP - Overcoming the Access-Control-Allow-Origin obstacle

I am attempting to enable another local host (such as javascript.dev) to make a xhr request to this particular host, which operates on an IIS7 server. When I perform a curl -I command, the headers I receive are as follows: HTTP/1.1 200 OK Content-Length: ...

Incorporating the elements of an array into an unordered list for a formatted list display

I have a list here <ul> <li> This is</li> <li> a very nice</li> <li> list</li> </ul> This is a very nice list and this code to insert the array elements into the list var names =["tom", " ...