Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from key/value array in JavaScript or jQuery

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.

like image 965
Ravi Teja Avatar asked Jun 24 '26 16:06

Ravi Teja


2 Answers

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

like image 144
Oleksandr T. Avatar answered Jun 26 '26 07:06

Oleksandr T.


You can use like:

var newObj = [];
$.each(obj.cities,function(k,v){
  newObj.push(v.city_name);
});
console.log(newObj);
like image 40
Shashank Avatar answered Jun 26 '26 05:06

Shashank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!