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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With