【发布时间】:2013-10-07 10:23:08
【问题描述】:
考虑以下 JSON:
{
"Company" : "ABC Company",
"Place" : {
"Bangalore" :{
"Address" : "MG Road",
"Phone" : ["988888","888866","365656"]
},
"Mubmai" : {
"Address" : "1st Main Road,West",
"Phone" : ["21212","123123","544455"]
}
}
}
现在我想将 JSON 展平,以便获得多个 JSON。对于上面的例子,扁平化的输出如下:
{
"Company" : "ABC Company",
"Place" : "Bangalore",
"Address" : "MG Road",
"Phone" : "988888"
},
{
"Company" : "ABC Company",
"Place" : "Bangalore",
"Address" : "MG Road",
"Phone" : "888866"
},
{
"Company" : "ABC Company",
"Place" : "Bangalore",
"Address" : "MG Road",
"Phone" : "365656"
},
{
"Company" : "ABC Company",
"Place" : "Mubmai",
"Address" : "1st Main Road,West",
"Phone" : "21212"
},
{
"Company" : "ABC Company",
"Place" : "Mubmai",
"Address" : "1st Main Road,West",
"Phone" : "123123"
},
{
"Company" : "ABC Company",
"Place" : "Mubmai",
"Address" : "1st Main Road,West",
"Phone" : "544455"
}
而且 JSON 结构不是固定的,它往往会发生变化,但扁平化仍然必须以相同的方式工作。有没有办法在 Node.js 中做到这一点?
【问题讨论】:
-
如果 JSON 结构发生变化,那么我看不出扁平化它的逻辑是如何相同的。
-
这不仅仅是扁平化。您还在阵列上展开/迭代。如果您的 JSON 中有多个数组怎么办。
-
“有什么最好的方法吗?”你试过什么方法?
-
使用
JSON.parse、isPlainObject、hasOwnProperty、recursion。现在开始挖掘。
标签: javascript json node.js