2

I have a JSON string.

var obj = {"cities":[{"city_name":"abc"},{"city_name":"xyz"}]}

How can I get the values for the key city_name, using JavaScript or JQuery, and get another array like:

["abc","xyz"]

I tried many ways but couldn't figure out.

twernt
  • 20,271
  • 5
  • 32
  • 41
Ravi Teja
  • 119
  • 1
  • 2
  • 13
  • Possible duplicate of [hash keys / values as array](http://stackoverflow.com/questions/10415133/hash-keys-values-as-array) – ColinE Feb 22 '16 at 16:48

2 Answers2

8

You can use .map

var obj = {"cities":[{"city_name":"abc"},{"city_name":"xyz"}]}
var result = obj.cities.map(function (el) {
   return el.city_name;
});
console.log(result);

if you use ES2015 you can also use .map with arrow function

var result = obj.cities.map(el => el.city_name);

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

You can use like:

var newObj = [];
$.each(obj.cities,function(k,v){
  newObj.push(v.city_name);
});
console.log(newObj);
Shashank
  • 2,010
  • 2
  • 18
  • 38