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