2

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.

1

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much @Alexander . It made things so easy.
1

You can use like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.