在多维数组中将子数组转换为字符串

时间:2019-07-10 13:29:36

标签: javascript arrays json react-native multidimensional-array

我正在尝试更新下面提到的多维JSON文件中的单个值(ElementStatus)。

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

这是代码


    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  


在遍历forEach循环之后,我得到了Array格式的ElementList。 但是我希望它是以前的字符串格式。

1 个答案:

答案 0 :(得分:1)

您显示的代码存在很多问题。您显示的数据不是正确的JSON格式,因此马上就会失败。

我对您的示例进行了重新整理,以显示带有JSON输出的正确输入。

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);
相关问题