2

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);

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help on this! I was wandering ... I also saw your first version (without mapAndJoin()) ... is doing it via a general function like mapAndJoin() just better practice in case of multiple outputs ... or are there even further pro arguments?
It's the DRY principle - don't repeat yourself. If you have several cases that use the same code, abstract it to a method. Now if I want to change the separator from a comma to a slash, I can change it in one place. In addition, handling new cases is very easy, just call the method again with different params. I can also test the abstraction, to ensure that it handles edge cases, such as empty arrays, non arrays, key not found, etc...
Good to know ... thanks for the additional information!
1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.