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);
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.