javascript - How to flatten up embedded JSON into multiple documents -
consider following json:
{ "company" : "abc company", "place" : { "bangalore" :{ "address" : "mg road", "phone" : ["988888","888866","365656"] }, "mubmai" : { "address" : "1st main road,west", "phone" : ["21212","123123","544455"] } } }
now want flatten json multiple json. above example flattened output follows:
{ "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" }
and json structure not fixed tend change, still flattening has work same way. there way in node.js?
there go : (jsb)
var t = []; (p in a.place) { var _=a.place[p]["phone"]; (i = 0; < _.length; i++) { var g = { company: a.company, place: p, address: a.place[p]["address"] }; g.phone = _[i]; t.push(g) } }
if add
console.log(json.stringify(t)
you'll this
[{"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"}]
Comments
Post a Comment