本文介绍了将嵌套JSON转换为Flat JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用javascript,我已经嵌套了来自mongodb的json对象。
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.
现在我想要使它成为平面json数组对象,结果应该是这样的。如果 c
有多个json对象,它应该使用相同的 a
创建一个新的json对象, b
value
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.
谢谢
推荐答案
这样做很容易。
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);
数据是你的数组。
这篇关于将嵌套JSON转换为Flat JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!