使用嵌套数组转换逗号分隔字符串中的JSON

时间:2017-11-11 13:45:42

标签: javascript jquery arrays json string

我知道那里有很多例子,但我仍然无法让它发挥作用。我有这样的JSON:

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

存储在sessionStorage.getItem(“profile”);

如何转换两个逗号分隔的字符串?喜欢......

AF,AX,AL
ii,pi

尝试失败:

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

或者:

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

2 个答案:

答案 0 :(得分:2)

您需要解析从sessionStorage获得的字符串,然后您可以映射并加入:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

一种方法

&#13;
&#13;
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);
&#13;
&#13;
&#13;