Altering the values of nested object properties

Currently, I am struggling to update the values of keys within an array of objects. The JSON structure of the object I'm working with is quite intricate, with each object in the array potentially containing a different number of keys. Here is a simplified version of the JSON:

var payload = {
    "data": {
        "form_values": {            
            "70f9": [
                {
                    "form_values": {
                        "6949": "drop"                       
                    },                    
                },
                {                   
                    "form_values": {                        
                        "6949": "drop"                        
                    },
                    
                },
                {                    
                    "form_values": {                        
                        "6949": "drop"                        
                    },
                    
                }
            ],            
        },        
    }
}

I have attempted to change the 'drop' values to 'active' as shown below:

for (var i = 0; i < payload.data.form_values['70f9'].length; i++ ){
    var payload.data.form_values['70f9'][i].form_values['6949'] = 'active'
}

Usually, this approach works fine, but for some reason, it is giving me trouble this time.

Answer №1

It appears that you are incorrectly declaring the variable within the loop:

 var payload.data.form_values['70f9'][i].form_values['6949'] = 'active'

You should remove the var statement like this:

for (var i = 0; i < payload.data.form_values['70f9'].length; i++ ){
   payload.data.form_values['70f9'][i].form_values['6949'] = 'active'
}

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 significance do the variables c and d hold in the context of bubble sort implementation in the C programming language?

Regarding the ascending order bubble sort, the process involves checking if index i is greater than index "i + 1". If it is, then a swap occurs, and this continues until the loop reaches its end. The loop repeats until all indices are in order, resulting i ...

Struggling to Parse JSON Arrays in Node.js

Embarking on a journey with Node JS and Express, I find myself facing the challenge of developing a small proof of concept API in Node. The main hurdle I'm currently encountering stems from my limited understanding of how to parse JSON arrays to extr ...

How to use the filter() method to filter an array of objects based on a nested array within each object

The following data presents a list of products along with their inventory information: const data = [ { id: 1, title: "Product Red", inventoryItem: { inventoryLevels: { edges: [{ node: { location: { name: "Warehou ...

What is the best way to utilize the oninput function in Jade?

input(type='range', id= 'inputSlider', min='0', max='255', value='50', step='1', oninput=showValue(this.value)) span#outputText 50 script. var socket = io.connect(); socket.on(& ...

Why is it important to use linting for JavaScript and TypeScript applications?

Despite searching extensively on Stack Overflow, I have yet to find a comprehensive answer regarding the benefits of linting applications in Typescript and Javascript. Any insights or resources would be greatly appreciated. Linting has become second natur ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...

Exploring the world of npm packages: from publishing to utilizing them

Exploring My Module npmpublicrepo -- package.json -- test.js The contents of package.json are as follows: { "name": "npmpublicrepo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Erro ...

Mastering Java - Chapter 25 - Dealing with Class Cast Exception when Using Generics with Lists and Arrays

Currently, I am engrossed in reading the second edition of Effective Java by Joshua Bloch, specifically item 25 on page 122. In this chapter, the author presents a code snippet which reads as follows: // Naive generic version of reduction - won't com ...

Having trouble adjusting the label fontSize in ReactJS when using semantic-ui-react?

Is there a way to decrease the size of the label for a form input? In this scenario, attempting to set the fontSize does not work: <Form.Input label="Username" style={{fontSize: '10px'}} /> Does anyone have any suggestions on how to res ...

An error has been encountered: JSONDecodeError Unable to find expected value at line 1, column 1 (character 0) While trying to address the previous error, a new exception occurred:

import urllib.request import json def printResults(data): theJSON = json.loads(data) if "title" in theJSON["metadata"]: print(theJSON["metadata"]["title"]) count = theJSON["me ...

Hiding rows in a Datatable

Assistance needed to conceal specific rows in the datatable, If the User opts for "Show All" from the dropdown menu, the entire datatable should be displayed, However, if the User chooses "Hide USA", I wish to hide the rows with the Country value set ...

What can I do to resolve a node server issue with the error message "npm ERR! code ELIFECYCLE npm ERR! errno 1"?

npm ERROR! code ELIFECYCLE npm ERROR! errno 1 npm ERROR! [email protected] start: node server npm ERROR! Exit status 1 npm ERROR! npm ERROR! Task failed at the [email protected] start script. npm ERROR! This may not necessarily be an ...

What is the method for inserting a line break into a string that is being transferred to a component in Next JS?

I am currently collaborating on a group project that involves developing a website. One of my team members created a ContentBlock component to facilitate the creation of new pages (see component code below). I have been working on a new page for the site a ...

What is the reason behind being able to store the result of a GetComponent<Camera> in a Behaviour array, but unable to do GetComponent<Camera>(out behaviourArray[X])?

I have been wondering why this piece of code works: Behaviour _BehaviourArray = new Behaviour[1]; BehaviourArray[0] = GetComponent<Camera>(); But this code does not work: Behaviour _BehaviourArray = new Behaviour[1]; TryGetComponent<Camera>(ou ...

Error encountered using jQuery $.post: TypeError - e.type is not a valid function

I'm currently in the process of developing a feedback script specifically for the ZetaBoards forum software. My approach has been to create a $.post function, but when I attempt to submit the form by clicking the submit button, all I get in return is ...

The form within the dynamically loaded AJAX content is malfunctioning

My webpage is set up to load content from a separate file (content.php) into a div and refresh it every 5 seconds. In the content.php file, I have a form (basic HTML without javascript) that works fine when accessed directly at (example.com/content.php). ...

Trouble with selecting portions of a string

Currently, I am working on a PHP loop that is responsible for generating HTML table data containing UPC code numbers (total of 129) along with their respective UPC barcode images. The naming convention of the barcode images differs from the UPC numbers in ...

Retrieve a prepared response from a TypeORM query

I need to retrieve all the courses assigned to a user with a simple query: There are 2 Tables: students & courses return await this.studentsRepository .createQueryBuilder('s') .leftJoinAndSelect('courses', 'c' ...

Module 'js' not found

Upon adding a request, I encountered this error message. I attempted npm install js and added var js = require("js") in my app.js file, but unfortunately it did not resolve the issue. My express server is running on localhost. Error: Cannot find module &a ...

The API rendering in Rails is incompatible with Chartkick

Having some difficulty creating a line chart using API data [{"Apr 11":{"count":150}},{"Apr 12":{"count":140}},{"Apr 13":{"count":160}}] I attempted the following: @metrics.each do |data| data.each do |key, value| render json: data(:key).count ...