javascript - Insert jsonobject into new array -
say have following jsonobject
var arraywithvaluesandgroups = [{ "testobject": "object1", "graphgroup": { "test": { "group": "a", "value": "6" }, "test2": { "group": "b", "value": "5" } } }, { "testobject": "object2", "graphgroup": { "test": { "group": "a", "value": "9" }, "test2": { "group": "b", "value": "12" } } }, { "testobject": "object3", "graphgroup": { "test": { "group": "a", "value": "99" }, "test2": { "group": "b", "value": "16" } } } ]
i want create new object groups , values have group should in array. example want above object converted bellow
{ "a": { "test1": { "0": "6", "1": "9", "2": "99" } }, "b": { "test2": { "0": "5", "1": "12", "2": "16" } } }
what strategy use?
try this.
concept of object , array important on js , code.
practice way.
var newobject = {}; for(var i=0,ilen=arraywithvaluesandgroups.length;i<ilen;i++){ var testgroupobject = arraywithvaluesandgroups[i]; console.log(testgroupobject); // { // "testobject": "object1", // "graphgroup": { // "test": { // "group": "a", // "value": "6" // }, // "test2": { // "group": "b", // "value": "5" // } // } // } var graphgroupobject = testgroupobject.graphgroup; console.log(graphgroupobject); // { // "test": { // "group": "a", // "value": "6" // }, // "test2": { // "group": "b", // "value": "5" // } // } var graphgroupobjectkeys=object.keys(graphgroupobject); for(var j=0,jlen=graphgroupobjectkeys.length;j<jlen;j++){ var graphgroupobjectkey = graphgroupobjectkeys[j]; console.log(graphgroupobjectkey) // keys test, test2 // graphgroupobject[graphgroupobjectkey] // { // "group": "a", // "value": "6" // } var group = graphgroupobject[graphgroupobjectkey].group; var value = graphgroupobject[graphgroupobjectkey].value; if(!newobject[group]){ newobject[group]={}; } if(!newobject[group][graphgroupobjectkey]){ newobject[group][graphgroupobjectkey]={}; } newobject[group][graphgroupobjectkey][i] = value; } }
Comments
Post a Comment