简体   繁体   中英

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.

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

You can use like:

var newObj = [];
$.each(obj.cities,function(k,v){
  newObj.push(v.city_name);
});
console.log(newObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM