简体   繁体   English

如何从JavaScript或jQuery中的键/值数组中获取值

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

I have a JSON string. 我有一个JSON字符串。

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: 如何使用JavaScript或JQuery获取关键city_name的值,并获取另一个数组,如:

["abc","xyz"]

I tried many ways but couldn't figure out. 我尝试了很多方法,但无法弄清楚。

You can use .map 您可以使用.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 如果您使用ES2015您还可以使用带arrow function .map

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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