Javascript嵌套JSON合并特定对象名称值作为字符串

时间:2019-02-22 12:41:06

标签: javascript json

使用香草Javascript,我想在下面的嵌套JSON示例中以字符串形式返回多个位置的城市名称。 由于JSON结构的复杂性(无法更改),因此无法使用push。这会导致单独的循环。

"locations":[
    {
      "location":{
          "city":"New place 1",
          "other":"random"
      }
    },
    {
      "location":{
          "city":"New place 2",
          "other":"random dom"
      }
    }
]

预期输出: “新地方1”,“新地方2”

谢谢。

6 个答案:

答案 0 :(得分:0)

或者,更简单的解决方案。

let locations = [
    {
      "location":{
          "city":"New place 1",
          "other":"random"
      }
    },
    {
      "location":{
          "city":"New place 2",
          "other":"random dom"
      }
    }
];

let Array = [];
locations.forEach(function(par){
  Array.push(par.location.city);
})

let str = "";
Array.forEach(function(par){
  str += par +", ";
});

str = str.slice(0,-2);
  

console.log(str);

答案 1 :(得分:0)

您可以使用.reducetemplate literals来构建您的字符串。在这里,我还使用了.slice来删除字符串末尾的逗号和空格:

const locs = {locations:[{location:{city:"New place 1",other:"random"}},{location:{city:"New place 2",other:"random dom"}}]},

res = locs.locations.reduce((acc, loc) => `${acc}${loc.location.city}, `, ``).slice(0,-2);
console.log(res);

如果只想将数组作为输出,则可以使用.map

 const locs = {locations:[{location:{city:"New place 1",other:"random"}},{location:{city:"New place 2",other:"random dom"}}]},
 
arr = locs.locations.map(loc => loc.location.city);
console.log(arr);

答案 2 :(得分:0)

您可以使用.map()

let locations = [
    {
      "location":{
          "city":"New place 1",
          "other":"random"
      }
    },
    {
      "location":{
          "city":"New place 2",
          "other":"random dom"
      }
    }
];

const result = locations.map(loc => loc.location.city);

console.log(result);
console.log(result.join(','));

答案 3 :(得分:0)

使用Array.mapArray.join

let locations = [{"location":{"city":"New place 1","other":"random"}},{"location":{"city":"New place 2","other":"random dom"}}];

let result = locations.map(v => '"' + v.location.city + '"').join(", ");
console.log(result);

答案 4 :(得分:0)

const locs = [
    {
      "location":{
          "city":"New place 1",
          "other":"random"
      }
    },
    {
      "location":{
          "city":"New place 2",
          "other":"random dom"
      }
    }
]

const res = locs.map(d => d.location.city).join(', ');
console.log(res); // "New place 1, New place 2"

locs.map(d => d.location.city).join(', ')

很简单

答案 5 :(得分:0)

使用mapString constructor的一个班轮

var a = {
  locations: [{
    location: {
      city: "New place 1",
      other: "random"
    }
  }, {
    location: {
      city: "New place 2",
      other: "random dom"
    }
  }]
}
console.log(String(a.locations.map(e => e.location.city)))