简体   繁体   中英

javascript - how to get object name or associative array index name?

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

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"

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(' ');
var names = Object.keys(list);

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 .

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.

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