Reeta
Reeta

Reputation: 83

Converting child array to string in multidimensional array

I am trying to update single value(ElementStatus) in below mentioned multidimentional JSON file.

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"}

Here is the code


    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  


After iterating through forEach loop,I m getting ElementList in Array format. But I want it in string format that is how it was earlier.

Upvotes: 2

Views: 75

Answers (1)

Three D Fish
Three D Fish

Reputation: 163

There are a number of problems with the code you show. The data you show is not in proper JSON format, so that will fail right off of the bat.

I have reworked your example to show proper input with JSON output.

let elementsName = "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==elementsName)
    {
      element.ElementStatus="completed"
    }
  });
let outputString = JSON.stringify(newData);
console.log(outputString);

Upvotes: 1

Related Questions