简体   繁体   中英

Convert JSON in comma separated string with nested array

I know there are a lot of examples out there, but still I can't get it working. I have a JSON like this:

{"domiciles":[{"country":"AF"},{"country":"AX"},{"country":"AL"}],"investor":[{"type":"ii"},{"type":"pi"}]}

stored in sessionStorage.getItem("profile");

How can I convert in two comma seperated strings? Like ...

AF,AX,AL
ii,pi

Failed attempts:

var dataResidence = sessionStorage.getItem("profile");
var resultResidence = dataResidence.map(function(val) {
  return val.country;
}).join(',');
console.log(resultResidence);

Or:

var newString = "";
for(var i=0; i< dataResidence.domiciles.length;i++){
    newString += userDefinedSeries.country[i];
    newString += ",";
}
console.log(newString);

You need to parse the string you get from the sessionStorage , then you can map and join:

 var profile = '{"domiciles":[{"country":"AF"},{"country":"AX"},{"country":"AL"}],"investor":[{"type":"ii"},{"type":"pi"}]}'; // sessionStorage.getItem("profile"); var dataResidence = JSON.parse(profile); function mapAndJoin(arr, key) { return arr.map(function(o) { return o[key]; }).join(); } var domiciles = mapAndJoin(dataResidence.domiciles, 'country'); var investor = mapAndJoin(dataResidence.investor, 'type'); console.log(domiciles); console.log(investor); 

One way of doing it

 var obj={"domiciles":[{"country":"AF"},{"country":"AX"},{"country":"AL"}],"investor":[{"type":"ii"},{"type":"pi"}]}; console.log(JSON.stringify(obj)); var countries = obj.domiciles; var str = ''; for(i=0;i<countries.length;i++){ if(i != countries.length - 1) str+= countries[i].country+","; else str += countries[i].country; } console.log(str); var type = obj.investor; var str1 = ''; for(i=0;i<type.length;i++){ if(i != type.length - 1) str1 += type[i].type+","; else str1 += type[i].type; } console.log(str1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM