Retrieve JSON or JavaScript property with a string reference

Consider the following JSON array:

_htaItems = [
    {"ID":1,
     "parentColumnSortID":"0",
     "description":"Precondition",
     "columnSortID":"1",
     "itemType":0},
    {"ID":2,
     "parentColumnSortID":"0",
     "description":"Precondition",
     "columnSortID":"1",
    "itemType":0}]

The goal is to update this array by providing the ID, column name, and new value as parameters to a function:

function updateJSON(ID, columnName, newValue)
{
    var i = 0;
    for (i = 0; i < _htaItems.length; i++)
    {
        if (_htaItems[i].ID == ID)
        {
            ?????
        }
    }
}  

The main question is how to perform the update. Typically, one could simply assign a new value like so:

 _htaItems[x].description = 'New Value'

However, in this case, the column name is provided as a string.

Answer №1

When working with JavaScript, there are two ways to access an object property. The first way is using literal notation:

the.answer = 42;

The second way is using bracketed notation with a string for the property name:

the["answer"] = 42;

Both of these methods achieve the same result. However, with the bracketed notation, you can use any expression that resolves to a string inside the brackets. This allows for more flexibility in setting object properties. For example:

x = "answer";
the[x] = 42;

x = "ans";
y = "wer";
the[x + y] = 42;

function foo() {
    return "answer";
}
the[foo()] = 42;

All of the above statements will set the answer property of the object the to 42.

If the value of description cannot be hardcoded and is passed from another source, you can utilize bracketed notation like this:

s = "description"; 
_htaItems[x][s] = 'New Value';

Answer №2

_htaItems[x][columnName] = 'Updated Content'; Was that not what you meant?

Answer №3

To update the value of a specific property, use

_htaItems[i][columnName] = newValue;
. This will modify the value assigned to the key indicated by columnName.

Answer №4

To successfully assign the new value to a specific column, make sure to utilize square bracket notation in the same way you did for array indexing:

_htaItems[i][columnName] = newValue;

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

Can a robust web application be developed using Kotlin in Node.js?

With the recent release of Kotlin 1.1, it is now possible to compile Kotlin projects into JavaScript as a target, allowing for full JavaScript compilation. Can a Node.js application, like an express webserver, be developed entirely using Kotlin code? As s ...

Submitting a form in PHP without refreshing the page

I am facing an issue with posting my form to Mysql without refreshing the page. I have tried looking for solutions online, but nothing seems to work. Can anyone assist me with this? <script> $('#submit').click(function() { $.ajax({ ...

Capture environmental data from JSON response in a Postman script

I have retrieved the following data: { "dbflash:db-files": { "db-file": [ { "usageStatus": "Backup", "dbFileName": "DB_1710013320170619041443", }, { "usageStatus": "Current", "dbF ...

What is the best approach for retrieving values from dynamically repeated forms within a FormGroup using Typescript?

Hello and thank you for taking the time to read my question! I am currently working on an Ionic 3 app project. One of the features in this app involves a page that can have up to 200 identical forms, each containing an input field. You can see an example ...

Arrange list items dynamically using ajax

I am attempting to adjust the positioning of the scrollable list item depending on whether a message was sent by a user or another party. However, my current method is not yielding the desired results. I have experimented with adding .css('position&a ...

Facing a problem with jQuery where variables are lost when using $(document).on

I am facing an issue with my code - when I remove the (doc on), it works fine until the div is reloaded. However, after the reload, the buttons stop working. When I add (doc on), the event triggers but drops the variables. Any suggestions? $(document). ...

Ways to retrieve the React Router match object in mapStateToProps

Is there a way to access the react-router match object for its params from mapStateToProps or any other selector? I'd like to use these params to generate a value that will be passed down as props to a presentational component within the selector. The ...

What is the best way to export fresh Django database records to JSON?

In setting up my Django app, I have included several .tsv files in the git repository that contain initial data to populate the database. This data is imported into the SQLite database during app setup, which is not stored within the git repo. For ongoing ...

Execute the JavaScript function window.print() with a designated URL provided

In my asp.net mvc 2.0, I have created a report in the View which includes a header, footer, and content from searching for each record. The goal is to provide users with a preview of what they want to print before allowing them to click on a link or button ...

The ngView directive is failing to display the specified templates

Having trouble rendering templates in ng-view on my Angular app when testing it across different browsers or on a localhost server using Node. The console isn't showing any errors, and after researching extensively online, I still haven't found a ...

What is the best way to implement an ng-change function on multiple fields within the same page without causing a cyclic call loop?

In my page, I have three angular-moment-datepicker fields - a date picker field, a month picker field, and a year picker field respectively. Here is the code: <input class="form-control" placeholder="BY DAY" ng-model="date" moment-picker="gDate" start- ...

When refreshed using AJAX, all dataTable pages merge into a single unified page

I followed the instructions on this page: How to update an HTML table content without refreshing the page? After implementing it, I encountered an issue where the Client-Side dataTable gets destroyed upon refreshing. When I say destroyed, all the data ...

Firebase Cross-Origin Resource Sharing (CORS) and IP range whit

Is there a way to whitelist two IP ranges in order to access my firebase cloud functions? I believe it should be possible to define them within this code snippet: const cors = require('cors')({ origin: true }); I tried searching on Google f ...

The TypeScript optional callback parameter is not compatible with the anonymous function being passed to it

Encountering an issue with TS callbacks and function signatures. Here is my scenario: ... //inside a class //function should accept a callback function as parameter refreshConnection(callback?: Function) { //do something //then ca ...

Tips for displaying dynamic content based on conditions in React

I am currently working on adjusting the boilerplate repository in order to render different pages based on whether a user is logged in or not. The current setup always displays the same page but includes additional content if there is an authenticated user ...

Determine the total sum of values for various keys that share the same ID in JavaScript

I am interested in finding a way to add together the values of multiple keys for the same ID in an object using JavaScript. Specifically, I want to sum the price and total keys for each unique ID in my object. var obj = [{ id: "1", price: 100, tot ...

Pass data dynamically to router in ExpressJS

Within my app.js file, there are several variables defined: var user = "max"; Additionally, there is a route function set up like so: app.post('/register', user.postRegister); In the /routes/user.js file, there is a module function structured ...

MongoDB encountering issue with pushing to array while retrieving schema using _id

I am currently working on implementing a subscription feature on my website where users can subscribe to classes and have them added to their class array in the user model. Below is the code I have written for this functionality: app.post("/subscribe", fu ...

Adding icons to form fields based on the accuracy of the inputs provided

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Assignment 2 - Website Bui ...

Discover every conceivable combination of items that results in the total values adding up to a specific number

Wanting to achieve this using TypeScript. I am dealing with an array of objects, each containing a property named rating. Here is how the array looks: const objects = [{"name":"foo","rating":4}, {"name":"bar","rating":5}, {"name":"foobar","rating":2}] G ...