Convert Nested JSON to Flat JSON

2019-06-13 01:39发布

问题:

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.