javascript - 如何获取对象名称或关联数组索引名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9650870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:20:36  来源:igfitidea点击:

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

javascriptjquery

提问by J Harri

I have a JSON object like such:

我有一个像这样的 JSON 对象:

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

How do I extract all the nameX string values?

如何提取所有 nameX 字符串值?

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

例如,假设我想将它们连接在一个字符串中输出,例如:“name1 name2”

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

在任何解决方案中使用 jQuery 都很好。请指教...

回答by pimvdb

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

要获取对象的键,Object.keys在 ES5 中有,它返回一个数组:

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

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

如果要过滤键,可以使用.filter

Object.keys(list).filter(function(key) {
  return key.indexOf("name") === 0; // filter keys that start with "name"
}).join(" "); // "name1 name2"

回答by mVChr

For older browsers that don't support keys:

对于不支持的旧浏览器keys

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

回答by mVChr

var names = Object.keys(list);

回答by jfriend00

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:

既然您说基于 jQuery 的解决方案会很好,那么这里有一种不需要 ES5 垫片的 jQuery 实现方法:

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

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

这里的工作演示: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.

jQuery.map()迭代对象的属性或数组的项,并根据我们传递给它的自定义函数构建一个新数组。然后我们只需将该数组的结果连接到一个字符串中。你可以在jQuery.map()这里阅读。