javascript - convert json object to json array of object -


i had received json snippet, has following lines (string converted json object)

"profile":{"id":"billg","name":"bill gates","countrycode":"us"} 

now user adds 1 more profile, need convert profile object array of profile objects.

"profile":[{"id":"billg","name":"bill gates","countrycode":"us"},{"id":"steve","name":"steve jobs","countrycode":"us"}] 

any pointers or code highly appreciated

it great if show code of yours: don't know what's source of json string (json = javascript object notation, 'json object' tautology), , don't know how second profile created.

consider this, though:

var jsondata = '{"profile":{"id":"billg","name":"bill gates","countrycode":"us"}}'; var data = json.parse(jsondata); // it's object now... var profile = data.profile; // storing object value of `.profile` property var anotherprofile = {"id":"steve","name":"steve jobs","countrycode":"us"}; if (! profile[0]) { // checking whether it's array or not // it's not, should make array, adding profile data.profile = [data.profile, anotherprofile]; } else { // if was, it'd enough push anotherprofile end of data.profile.push(anotherprofile); } console.log(data); 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

c++ - Accessing inactive union member and undefined behavior? -

php - Get uncommon values from two or more arrays -