Update values in a JSON object

Here is a JSON data structure that I am working with:

var jsonData = [
    {
        "id": "1",
        "key1": "Name1",
        "key2": 2,
        "key3": 1
    },
    {
        "id": "2",
        "key1": "Name2",
        "key2": 2,
        "key3": 1
    }, 
    {
        "id": "3",
        "key1": "Name3",
        "key2": 2,
        "key3": 1
    }
]

I have a requirement to replace one object with another within this array. For example, I need to update:

{
    "id": "2",
    "key1": "Name2",
    "key2": 2,
    "key3": 1
}

with

{
    "id": "5",
    "key1": "Name7",
    "key2": 3,
    "key3": 2
}

At the moment, I am able to filter out the specific object from the array:

var idToReplace = 2;
var newObj = {"id": "5", "key1": "Name7", "key2": 3, "key3": 2};
var filteredData = jsonData.filter(function(element) {
     return element.id === idToReplace;
});
console.log(filteredData);

What steps should be taken next in order to replace an object with id === 2 with the newObj?

Answer №1

If you're looking for a way to find the index of an element in an array, you can utilize the method Array.prototype.findIndex():

var id = "2"; // ids are strings in your json object
var newObj = {"id": "5", "key1": "Name7", "key2": 3, "key3": 2};
var idx = json.findIndex(function(el) {
    return el.id === id;
});
if (~idx) { // this checks if idx is greater than -1
    json[idx] = newObj;
}

Keep in mind that findIndex may not be supported in all browsers, so it's a good idea to verify compatibility on MDN.

An alternative approach for better cross-browser support is replacing findIndex with reduce:

var idx = json.reduce(function(r, el, i) {
    return !~r && el.id === id ? i : r;
}, -1);

Answer №2

In JavaScript, the === operator signifies "equality without type coercion", allowing you to compare values regardless of their data types.

const id = 2; // id is a number, but json[i].id may be a string
const newObj = {"id": "5", "key1": "Name7", "key2": 3, "key3": 2};
const filteredResults = json.filter(function(element) {
     return element.id === String(id); // Alternatively, use id.toString() or id + ''
});
console.log(filteredResults);

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

What is the best way to display a single object from an array once data is retrieved from an API

Having trouble mapping out the individual driver from the JSON array that was generated. Can't seem to get it into a list or anything. JSON: [{"driver_id":"0-ikkpyhyjg9","location":{"latitude":null,"longit ...

Javascript code for populating multiple objects with new items using a nested for loop

Trying to articulate my thoughts, I am interested in linking a list of skill sets to various individuals within their respective lists. For instance: I possess a Json object detailing individuals: "people": [ { "id": 1, "name": "Tony ...

Importing a third-party JavaScript library in Angular 2 RC5: Utilizing Showdown Library

Struggling with the integration of Showdown as a vendor in my project. Whenever I compile, the browser console throws an error saying showdown is not defined. Since it's a vendor package, importing it directly into app.module.ts doesn't seem to b ...

Using Function Call to Generate Components in React

Being tired of repeatedly defining states to render Components based on conditions, I often find myself just wanting to display notifications or alerts. My current dilemma is figuring out how to render a component by invoking a function from within that co ...

The function str.split() is dividing the text based on individual letters rather than the specified delimiter

I am facing an issue where the string of tags retrieved from firebase needs to be split by ',' and stored in the data() for rendering. The firebase snapshot data is correctly formatted after splitting when viewed in the console like this: "t ...

Shifting HTML table in Javascript by toggling checkboxes

When I click the checkbox, the table elements are not displaying inline. I am simply hiding the class "box". Do I need to write a special format? By default, the elements are displayed inline but when I check the checkbox, they shift. The column 'Stat ...

Embedding a thread in an HTML document (Difficult task)

I'm currently working on a method to achieve the following task: Embedding a specific string (such as "TEST") into the content of an HTML page, after every certain number of words (let's say 10). The challenge here is ensuring that the word count ...

Insert this HTML table along with radio buttons into an Excel spreadsheet

My HTML table contains rows with a variety of content, including plain text characters and elements like radio buttons and lists. I want users to be able to copy-paste the table into MS Excel as plain text and have the radio button values replaced with "c ...

I need help with this Jquery code - trying to target an element with a specific attribute value. What am I missing here?

I am attempting to selectively add a border around the .L1Cell element where the attribute name parent is equal to Workstation. However, it appears to be applying the border to all .L1Cell elements. Here is the link to the JSFIDDLE $(document).ready(func ...

Create a timestamp with Javascript rendering

Looking to convert a Unix timestamp into a human-readable format without adjusting for my browser's timezone. For example, if the timestamp is 1400167800 (05 / 15 / 14 @ 3:30:00pm UTC) and my timezone is +2, how can I display this timestamp as ' ...

Angular-powered SPAs with cookie authentication

My current web framework utilizes cookie (or token) based authentication. Upon user registration, a postback occurs and the server embeds an authentication token into a cookie which is then linked to the user's browser. Subsequent requests utilize thi ...

When pressing the "back" button in the browser, the page displays JSON data instead of HTML, which is achieved by utilizing Rails and d3.js programming

Creating a visualization in Rails with a d3.js JSON callback can be done like this: View d3.json(document.URL, function(data){ // create visualization } Controller def index respond_to do |format| format.html do # render th ...

Customized Wordpress Plugins

I am excited to be working on my first Wordpress website and incorporating a custom carousel for the first time. I stumbled upon this amazing idea on Codepen. http://codepen.io/supah/pen/zZaPeE Further exploring, I found this repository as well: https:/ ...

React-Native Error: Invalid element type detected

While attempting to run my React Native app on my iPhone using Expo, I encountered an error displayed in a red background area. Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

What methods do current web browsers utilize to implement the JS Array, particularly when it comes to adding

When using the .push() method on an Array object in JavaScript, the underlying "array" capacity increases as more elements are added. If anyone knows of a reliable resource for this type of information regarding JavaScript, please feel free to share. upda ...

Comparison between WAMP and Live server integration with Facebook for connecting applications

I've been facing some challenges while integrating my website with Facebook Connect. I have been following the instructions provided in this guide. When attempting to run the following code from localhost, please note that for security reasons, my ap ...

The requested resource at http://127.0.0.1:8000/storage/profiles/ could not be located (Error 404: Not

I have successfully implemented a feature on my website that allows users to upload their avatar picture using Vue.js and Laravel as the backend. The image is stored in the storage directory, and I can display it on the user's profile page using Vue.j ...

The function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

Ways to remove an item from firebase database

Currently, I am exploring ways to delete data stored in the Firebase database specifically under the requests category. Check out this example Below are the functions I have implemented to fetch and manipulate the data: export default { async contactArtis ...

Should I wait for my state to be updated with new information before triggering the render function?

Can someone assist me with restructuring the code below to ensure that the information in the data array is displayed on the initial page load? async componentDidMount() { const { id } = this.props.match.params const soccerApi = axio ...