8

I have a JSON object like such:

var list = {'name1' : {'element1': 'value1'}, 'name2' : {'element1': 'value2'});

How do I extract all the nameX string values?

For example, suppose I want to output them concatenated in a string such as: "name1 name2"

Use of jQuery in any solution is fine. Please advise...

4 Answers 4

15

To get the keys of an object, there is Object.keys in ES5, which returns an array:

Object.keys(list).join(" "); // "name1 name2"

If you want to filter the keys, you can use .filter:

Object.keys(list).filter(function(key) {
  return key.indexOf("name") === 0; // filter keys that start with "name"
}).join(" "); // "name1 name2"
Sign up to request clarification or add additional context in comments.

1 Comment

One note, though--the keys method was introduced in 1.8.5+. If you need back-compatibility, you might prefer to use an alternative like the _.keys shim from underscore.js (@mVChr's answer offers another)
5
var names = Object.keys(list);

Comments

4

For older browsers that don't support keys:

var list_keys = []
for (var n in list) {
    list_keys.push(n)
}
var names = list_keys.join(' ');

1 Comment

You should include a hasOwnProperty test: if (list.hasOwnProperty(n)).
2

Since you said a jQuery-based solution would be fine, here's a way to do it with jQuery that doesn't require an ES5 shim:

var itemString = $.map(list, function(item, key) {
    return(key);
}).join(" ");

Working demo here: http://jsfiddle.net/jfriend00/a2AMH/

jQuery.map() iterates over the properties of an object or the items of an array and builds a new array based on the custom function we pass to it. We then just join the results of that array into a string. You can read about jQuery.map() here.

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.