Converting a nested array of children into a string within a multidimensional array

I am currently in the process of updating a single value (ElementStatus) within the multidimensional JSON file shown below.

BuildingID: 1521
BuildingName: "PEN LLOYD BUILDING"
BuildingNumber: "A"
ElementList: Array(15)
0: {ElementID: 114, SurveyTypeID: 3, Code: "M.01.01.01", ElementDescription: "M.01.01.01 Boilers/Plant", ElementStatus: "null"}
1: {ElementID: 115, SurveyTypeID: 3, Code: "M.01.01.02", ElementDescription: "M.01.01.02 Heat Emitters", ElementStatus: "null"}
2: {ElementID: 116, SurveyTypeID: 3, Code: "M.01.01.03", ElementDescription: "M.01.01.03 Distribution", ElementStatus: "completed"}

Below is the code snippet


    var newData = JSON.parse(success);                      
     const data1 = newData[0].results.recordset[0].ElementList;
     //console.log(data1.toArray());              
     var array = JSON.parse(data1);
     array.forEach(function(element){
      if(element.ElementDescription == elementsName)
       {
          element.ElementStatus = "completed";
       }
     })  
     newData[0].results.recordset[0].ElementList = array;


Upon completion of the forEach loop, I am obtaining the ElementList in Array format. However, I require it in string format as it was previously.

Answer №1

The code you provided has several issues. Firstly, the data does not adhere to the correct JSON format, causing immediate failure.

To rectify this, I have modified the code to display proper JSON input and output.

let elementName = "M.01.01.01 Boilers/Plant";
let success = `{"BuildingID": 1521,
"BuildingName": "PEN LLOYD BUILDING",
"BuildingNumber": "A",
"ElementList": 
[{"ElementID": 114, "SurveyTypeID": 3, "Code": "M.01.01.01", "ElementDescription": "M.01.01.01 Boilers/Plant", "ElementStatus": null},
{"ElementID": 115, "SurveyTypeID": 3, "Code": "M.01.01.02", "ElementDescription": "M.01.01.02 Heat Emitters", "ElementStatus": null},
{"ElementID": 116, "SurveyTypeID": 3, "Code": "M.01.01.03", "ElementDescription": "M.01.01.03 Distribution", "ElementStatus": "completed"}]}`;

let newData = JSON.parse(success);                      
newData.ElementList.forEach(function(element) {
  if (element.ElementDescription == elementName) {
    element.ElementStatus = "completed";
  }
});
let outputString = JSON.stringify(newData);
console.log(outputString);

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

Having trouble sending the selected value from a dropdown list to the server using $.ajax

I am embarking on my first project using JQuery (jquery-3.0.0.min.js) and JavaScript. My goal is to build a straightforward web form that connects to a database through a Web API. The form consists of various input text fields and two select dropdowns. ...

Riot.js effortlessly generates custom tags nested within each other from various server-side files

My goal is to utilize riot.js server-side rendering in order to create a static HTML page that can be indexed by search engine spiders. I have managed to get a basic example up and running, but I am now trying to solve the challenge of dynamically loading ...

Having trouble accessing JSON data from a Google spreadsheet?

Yesterday I was successfully retrieving JSON data from a spreadsheet, but now it's returning null. Strangely, I am not able to fetch JSON from a particular spreadsheet file anymore. However, if I create a new spreadsheet and use the exact same code, i ...

Discover a simpler method for grouping 2-dimensional scatter data into a gridded array format

After discovering a technique for clustering dispersed point data into a structured 2-D array similar to the rasterize function, I am eager to explore more efficient methods to achieve this goal. The Method 1. Introduction 1000 points of data with thre ...

Using React hooks to reset state in a reducer: step-by-step guide

event.js import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useHistory } from 'react-router-dom'; import { addEvent } from '../actions/event'; ...

Encountering issue with jQuery - Ajax causing error 500 for select posts

Recently, I encountered an issue with the Ajax functionality on a live website. It was previously working perfectly fine, but suddenly started returning a 500 internal server error instead of the expected page. Oddly enough, I discovered that I could stil ...

Tips for removing the "" character from a JSON string using JavaScript

At my node js server, I am receiving a json string that has the following format: {\"gID\":1,\"sID\":18,\"T\":\"Parking\"} I added the "\" in the string because it was created in C and the \ is used to es ...

Solidity: Issue with Array Equality Operator

I recently wrote a basic solidity program: //SPDX-License-Identifier: MIT pragma solidity 0.8.16 ; contract arrayExample { uint256[] public numbers ; uint256 index = 0 ; function addNumber(uint256 num) public { numbers[ind ...

There is a lack of communication between the tomcat application and the database

I am currently working on a web application that is stored in a war file and runs with Tomcat. Initially, I start my MySQL 5.7 database, followed by running a Spring Boot project created with the necessary files. After completing these steps, I deploy my ...

The contents of Ionic views are not stored in a cache, so the controller must

In my ionic application, I have several views. When I launch the app, it takes me to the main view where data is loaded upon initialization of the controller. The issue arises when I navigate away from this view using tabs; sometimes the controller gets d ...

Troubleshooting app crashes in Android Studio caused by HttpURLConnection

Having recently ventured into Android and Java development, I am currently employed as a web developer but eager to expand my skills by learning Android Studio and Java. When learning a new language, my usual first step is to make a database call, in this ...

Utilizing @PathVariable in Spring to handle Strings with IP addresses without needing a trailing slash

This snippet is a segment of my controller code: @RequestMapping(value="/json/getPCs/{serverAddress}", method=RequestMethod.GET) public @ResponseBody List<PC> getPCForServerJSON(@PathVariable String serverAddress) { logger.info("Server address: ...

When using JavaScript with React, setting a value after the onBlur event can result in users having to click

In my React form, I have an input button with an onBlur event that sets the value to a useState property. However, after the onBlur event is triggered, the user has to click the button twice to focus on it properly. It seems like the page needs time to pro ...

Failure to update the DOM after clicking a button and making an AJAX request

After experimenting with different iterations of this code, the outcomes have been mediocre and inconsistent. The concept is rather simple: A user inputs a search query into a text box, clicks a button, and the query is assigned to a var search. This varia ...

Troubleshooting AngularJS $q Promise Not Being Returned

I have encountered an issue while trying to call a service method in AngularJS. The service method is being called successfully, but it is not returning any value to the controller function that invoked it. If anyone can offer assistance, I would greatly ...

The value of React state may be unpredictable, even if it appears to be defined on the

<li className="field-title">Role: </li> {console.log(this.state.userData.roles)} {this.state.userData.roles.map((role) => { return ( <li>{role.name}</li> ) })} Even though when I console log the state ...

Is there a way to update JSON data in Swift 3 when the save button is clicked?

After logging in, I saved my user JSON data on the key "user". How can I update this value when I press the save button? For example, changing the value of "crew_preferred_name" to "Xiao Pang". UserDefaults.standard.set(json, forKey: "json") user = UserDe ...

Jackson Mixin: for deserializing route identifiers

I have implemented the Jackson Mixin for deserializing a mongo object and this is how my Mixin looks: public interface MyMixin { /** * Mixin to set key value for pojo. * @param key key * @param value value */ @JsonAnySetter void put(Stri ...

Integrate Javascript code into a JavaScript file

Is there a way to incorporate a JavaScript link inside a .js file? Does a .js file support include, require, or import similar to CSS or PHP? Here is the code in question: // Global site tag (gtag.js) - Google Analytics var script = document.createElemen ...

Trouble with Angular: Passing output between child components is not working

Just dipping my toes into Angular, I started learning it yesterday for a take-home job interview project. Please excuse any rookie mistakes in advance. For some hands-on practice, I decided to work on a basic project where the main component (app) has two ...