【问题标题】:Converting child array to string in multidimensional array将子数组转换为多维数组中的字符串
【发布时间】:2019-11-20 03:31:40
【问题描述】:

我正在尝试更新下面提到的多维 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 循环后,我得到了数组格式的 ElementList。 但我希望它是字符串格式,就像以前一样。

【问题讨论】:

  • 所以你将它解析为数组.....用 stringify 撤消它。似乎是一个非常明显的问题

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


【解决方案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);

【讨论】:

  • newData.ElementList.forEach(function(element){ if(element.ElementDescription==elementsName) { element.ElementStatus="completed" } });无法读取未定义的属性'forEach'跨度>
  • 检查 ElementList 是正确的名称,并且它实际上是一个数组。这是演示代码的工作:jsfiddle.net/o58ygwLe
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 2012-11-17
相关资源
最近更新 更多