Convert Nested JSON to Flat JSON

假如想象 提交于 2020-01-01 23:55:10

问题


I am using javascript and I have nested json object getting from mongodb.

"abc": [
    {
      "a": "01AABCE2207R1Z5",
      "b": "Y",
      "c": [
        {
          "ca": "A",
          "cb": "AflJufPlFStqKBZ",
          "cc": "S008400"
         },
         {
          "cx": "A",
          "cy": "AflJufPlFStqKBZ",
          "cz": "S008400"
         }
        ]
     },

      {
      "a": "01AABCE2207R1Z5",
      "b": "Y",
      "c": [
        {
          "ca": "A",
          "cb": "AflJufPlFStqKBZ",
          "cc": "S008400"
         },
         {
          "cx": "A",
          "cy": "AflJufPlFStqKBZ",
          "cz": "S008400"
         }
        ]
     }
    ]

Above schema have fixed fields there will no changes in schema.

Now I want to make it as flat json array object and result should be like that. If c has multiple json object the it should create a new json object with the same a, b value

 [{
     "a": "01AABCE2207R1Z5",
     "b": "Y", 
     "ca": "A",
     "cb": "AflJufPlFStqKBZ",
     "cc": "S008400" 
    },
{
     "a": "01AABCE2207R1Z5",
     "b": "Y",  
     "cx": "A",
     "cy": "AflJufPlFStqKBZ",
     "cz": "S008400"
    },
    {
     "a": "01AABCE2207R1Z5",
     "b": "Y", 
     "ca": "A",
     "cb": "AflJufPlFStqKBZ",
     "cc": "S008400" 
    },
    {
     "a": "01AABCE2207R1Z5",
     "b": "Y",  
     "cx": "A",
     "cy": "AflJufPlFStqKBZ",
     "cz": "S008400"
    }
    ]

So, I want to know the fast and easy steps to make it flat. Please let me know the process and methods to solve this.

Thanks


回答1:


It is so easy to do this.

var flatArray = [];
var flatObject = {};

for (var index = 0; index < data.length; index++) {
  for (var prop in data[index]) {

    var value = data[index][prop];

    if (Array.isArray(value)) {
      for (var i = 0; i < value.length; i++) {
        for (var inProp in value[i]) {
          flatObject[inProp] = value[i][inProp];
        }
      }
    }else{
        flatObject[prop] = value;
    }
  }
  flatArray.push(flatObject);
}

console.log(flatArray);

data is your array.



来源:https://stackoverflow.com/questions/44648663/convert-nested-json-to-flat-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!