Modify an aspect of the object and return it

After receiving a JSON object from an API, I am looking for a way to update only one user within the object. For example, let's say I want to update userId 4 without having to modify the entire JSON structure.

Instead of updating the user individually by ID, I am interested in making partial updates to the JSON and then posting back the complete object. This functionality is similar to how Git allows users to update or add specific lines of code.

If my explanation is unclear, please feel free to ask for clarification. Any assistance on this matter would be greatly appreciated. Thank you.

Answer №1

To modify an array, you can utilize the Array.map method. Here's how:

const modifiedArray = YourArray.map((element, index, array) => {
   if (element.userId === 4) {
      // perform a task on this element
   }
});

The Array.map method will give back the altered array.

Answer №2

const data = [
  { id: 1, name: "John", age: 30 },
  { id: 2, name: "Jane", age: 25 },
  { id: 3, name: "Bob", age: 40 }
];

const index = data.findIndex(item => item.id === 2);
data[index].name = "Janet";
data[index].age = 27;
console.log("Updated data object: ", data[index]);

Answer №3

let elements = [
{
    id: 1,
    name: "John",
    age: 25
},
{
    id: 2,
    name: "Emily",
    age: 30
},
{
    id: 4,
    name: "Mark",
    age: 35
}
];

function findElementWithId4(element) {
 return element.id === 4;
};

const foundIndex = elements.findIndex(findElementWithId4);

elements[foundIndex].name = "newName";

console.log(elements[foundIndex])

Answer №4

One effective approach involves utilizing the array.map function.

Answer №5

Typically, when working on such tasks, it is recommended to structure your JSON in the following way:

const database = {
  1:{
    userId: 1,
    title: "title1",
    body: "body1"
  },
  2:{
    userId: 2,
    title: "title2",
    body: "body2"
  },
  4:{
    userId: 4,
    title: "title4",
    body: "body4"
  }
}

From there, you can easily make updates to a specific user's information like so:

database[4]["body"] = "body4 updated value"

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

Updating the view in AngularJS with a service to keep users engaged even when they are offline

I'm currently developing an application that requires the ability to detect when a user loses internet connection or is unable to reach the server. Various controllers and services should be able to check and update this status easily. I have successf ...

Obtain the default/initial argument type of typescript for extension purposes

Currently, I am in the process of developing code that automatically generates type hints based on function calls related to GraphQL Nexus tasks. In one of its functions, it requires an anonymous type constructed from the attributes generated automaticall ...

Navigating the DOM in Vue.js: A Step-by-Step Guide

While I am trying to utilize Vue.js to access the DOM, the code I have written within the mounted() lifecycle is not producing any results. Interestingly enough, the same code functions perfectly fine when using vanilla JavaScript. I have incorporated the ...

Unable to locate the name 'JSON' in the typescript file

I have been working on an angular application where I have implemented JSON conversion functionalities such as JSON.stringify and JSON.parse. However, I encountered an error stating 'Cannot find name 'JSON''. Furthermore, there is anoth ...

Adjusting the background hue of a bootstrap panel

I'm attempting to utilize JavaScript to change the background color of a panel in order to create a "selected" effect. Upon clicking, I retrieve the div by its ID and modify its background color. Although it initially works as intended, the backgrou ...

Exploring the process of breaking down a substantial string object into manageable key/value pairs using AngularJS

I gathered information from a text file called sample_resume.txt Name: John Doe Phone: (555) 555-5555 Email: [email protected] TARGET To succeed in the field of web development. SKILL SET Development: HTML5, JavaScript, Bootstrap, AngularJS, Rea ...

Angular2 - How to track or listen for (click) events on dynamically inserted HTML elements

I'm trying to inject a string with a dynamically retrieved (click) event into an Angular2 template. Since this string is fetched from the back-end after the DOM is loaded, Angular doesn't recognize the injected event. Here's an example of t ...

Utilizing AngularJs to retrieve data through the $http get method

Struggling to pass data back to my controller from my service without success. The service works as I can see the response in console log, but not in the controller. Service: (function () { angular .module('app') .service('testServ ...

Obtain EmberJS Data from File in a Synchronous Manner

New to JavaScript and working on an EmberJS app. Seeking guidance on synchronously loading Ember data fixtures from a JSON file. Any tips or recommendations are greatly appreciated! ...

What is the best way to eliminate the background color from one span after selecting a different one?

I created a span element that changes its background color when clicked, but I want the background color to switch to the newly clicked span while removing it from the previously clicked one. Can someone help me achieve this? CSS list-sty ...

Using a for loop to combine JSON objects when a shared attribute is identified

New to Python so please be patient with me. I have a dataset that looks like this: [ { "Created": "2022-07-04 13:27:35 UTC", "Text": "Text" }, { "Created": "2022-07-04 13:3 ...

Is it possible to extract a nested JSON array within an object using Retrofit?

My challenge is to extract and display the JSON array payment_details from the data list of objects. While I have successfully parsed the data array for display in a recycler view, I am facing difficulties in accessing the payment_details array. Custom A ...

You cannot access the property 'subscribe' on a void type in Angular 2

fetchNews(newsCategory : any){ this.storage.get("USER_INFO").then(result =>{ this.storage.get("sessionkey").then(tempSessionKey =>{ this.email = JSON.parse(result).email; this.newSessionKey = tempSessionKey; this.authKey =JSON.stringify("Basic ...

I'm looking to utilize this script to generate multiple buttons that insert content into a textarea. How can

Finally, I stumbled upon a script that enables undo/redo functionality for programmatically inserted text. You can find it here. If you want to check out the original script demo, click here. Here is the initial script: <div class="snippet" data-lang= ...

What is the best way to implement a progress bar for a fetch API call in a React Native application?

Attempting to create a progress counter that goes from 0% to 100% while fetching weather data in my program. The API request is initiated by getLocation() within index.ios.js, which in turn triggers fetchWeather() located in weatherApi.js. Is there a metho ...

Achieving multiple relationships with the same id and type in JSON: A simple guide

My project requires fetching data from the database based on ID. The records can have multiple values for the same ID and type, as they are of type history. The versions that we use change every time. I am utilizing Java8, rest-api, and json api where I ma ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Displayed information on hover

https://i.sstatic.net/XVQWG.jpg I've been searching high and low for a simple textbox that appears when you hover over an image, positioned either to the left or the right. I don't need anything too fancy - just a rectangular box with a backgrou ...

Encountering error code 2064 without any clear explanation in sight

Hey, I'm currently facing an issue while uploading values to a MySQL table from Node.js. The error 1064 keeps popping up, indicating that the query is badly formatted. However, I can't seem to pinpoint the exact problem. Here's the query in ...

What is the process of integrating an HTML web component with an HTML file? Can I use innerHTML = foo("myfile.html") to achieve

Using HTML web components allows me to define their code using this method: this.innerHTML = `<h1></h1>`; However, I find it cumbersome as I do not have access to the Emmet Abbreviation feature which slows down my component creation process. ...