admin管理员组文章数量:1126130
Say I create an object thus:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:
keys == ["ircEvent", "method", "regex"]
Say I create an object thus:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:
keys == ["ircEvent", "method", "regex"]
Share
Improve this question
edited Apr 18, 2018 at 13:51
Ciro Santilli OurBigBook.com
381k117 gold badges1.3k silver badges1.1k bronze badges
asked Oct 16, 2008 at 10:08
johnstokjohnstok
98.2k12 gold badges56 silver badges76 bronze badges
2
|
18 Answers
Reset to default 1232In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:
var keys = Object.keys(myObject);
The above has a full polyfill but a simplified version is:
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
Alternatively replace var getKeys
with Object.prototype.keys
to allow you to call .keys()
on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.
As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
/* useful code here */
}
}
As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. Object.keys()
will do what you want and is supported in Firefox 4, Chrome 6, Safari 5 and IE 9.
You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. Here's a more compatible solution:
Object.keys = Object.keys || (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
DontEnums = [
'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
],
DontEnumsLength = DontEnums.length;
return function (o) {
if (typeof o != "object" && typeof o != "function" || o === null)
throw new TypeError("Object.keys called on a non-object");
var result = [];
for (var name in o) {
if (hasOwnProperty.call(o, name))
result.push(name);
}
if (hasDontEnumBug) {
for (var i = 0; i < DontEnumsLength; i++) {
if (hasOwnProperty.call(o, DontEnums[i]))
result.push(DontEnums[i]);
}
}
return result;
};
})();
Note that the currently accepted answer doesn't include a check for hasOwnProperty() and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.
Implementing Object.keys() will give you a more robust solution.
EDIT: following a recent discussion with kangax, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his Object.forIn()
function found here.
Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.
For example:
var o = {"foo": 1, "bar": 2};
alert(Object.keys(o));
ECMAScript 5 compatibility table
Description of new methods
Object.getOwnPropertyNames(obj)
This function also shows non-enumerable properties in addition to those shown by Object.keys(obj)
.
In JS, every property has a few properties, including a boolean enumerable
.
In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.
Example:
var o = Object.create({base:0})
Object.defineProperty(o, 'yes', {enumerable: true})
Object.defineProperty(o, 'not', {enumerable: false})
console.log(Object.getOwnPropertyNames(o))
// [ 'yes', 'not' ]
console.log(Object.keys(o))
// [ 'yes' ]
for (var x in o)
console.log(x)
// yes, base
Also note how:
Object.getOwnPropertyNames
andObject.keys
don't go up the prototype chain to findbase
for in
does
More about the prototype chain here: https://stackoverflow.com/a/23877420/895245
I'm a huge fan of the dump function.
Ajaxian » JavaScript Variable Dump in Coldfusion
Download the dump function
Could do it with jQuery as follows:
var objectKeys = $.map(object, function(value, key) {
return key;
});
if you are trying to get the elements only but not the functions then this code can help you
this.getKeys = function() {
var keys = new Array();
for(var key in this) {
if( typeof this[key] !== 'function') {
keys.push(key);
}
}
return keys;
}
this is part of my implementation of the HashMap and I only want the keys, "this" is the hashmap object that contains the keys
This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.
var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);
Use Reflect.ownKeys()
var obj = {a: 1, b: 2, c: 3};
Reflect.ownKeys(obj) // ["a", "b", "c"]
Object.keys and Object.getOwnPropertyNames cannot get non-enumerable properties. It's working even for non-enumerable properties.
var obj = {a: 1, b: 2, c: 3};
obj[Symbol()] = 4;
Reflect.ownKeys(obj) // ["a", "b", "c", Symbol()]
Under browsers supporting js 1.8:
[i for(i in obj)]
Mozilla has full implementation details on how to do it in a browser where it isn't supported, if that helps:
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
};
})();
}
You could include it however you'd like, but possibly in some kind of extensions.js
file at the top of your script stack.
With ES6 and later (ECMAScript 2015), you can get all properties like this:
let keys = Object.keys(myObject);
And if you wanna list out all values:
let values = Object.keys(myObject).map(key => myObject[key]);
Building on the accepted answer.
If the Object has properties you want to call say .properties() try!
var keys = Object.keys(myJSONObject);
for (var j=0; j < keys.length; j++) {
Object[keys[j]].properties();
}
Since I use underscore.js in almost every project, I would use the keys
function:
var obj = {name: 'gach', hello: 'world'};
console.log(_.keys(obj));
The output of that will be:
['name', 'hello']
IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.
It seems stackoverflow does some stupid filtering.
The list is available at the bottom of this google group post:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0
A lot of answers here... This is my 2 cents.
I needed something to print out all the JSON attributes, even the ones with sub-objects or arrays (parent name included).
So - For this JSON:
mylittleJson = {
"one": "blah",
"two": {
"twoone": "",
"twotwo": "",
"twothree": ['blah', 'blah']
},
"three": ""
}
It'd print this:
.one
.two.twoone
.two.twotwo
.two.twothree
.three
Here is function
function listatts(parent, currentJson){
var attList = []
if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length > 0) {
return
}
for(var attributename in currentJson){
if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) {
childAtts = listatts(parent + "." + attributename, currentJson[attributename])
if (childAtts != undefined && childAtts.length > 0)
attList = [...attList, ...childAtts]
else
attList.push(parent + "." + attributename)
}
}
return attList
}
mylittleJson = {
"one": "blah",
"two": {
"twoone": "",
"twotwo": "",
"twothree": ['blah', 'blah']
},
"three": ""
}
console.log(listatts("", mylittleJson));
Hope it helps too.
The solution work on my cases and cross-browser:
var getKeys = function(obj) {
var type = typeof obj;
var isObjectType = type === 'function' || type === 'object' || !!obj;
// 1
if(isObjectType) {
return Object.keys(obj);
}
// 2
var keys = [];
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
keys.push(i)
}
}
if(keys.length) {
return keys;
}
// 3 - bug for ie9 <
var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
if(hasEnumbug) {
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
var nonEnumIdx = nonEnumerableProps.length;
while (nonEnumIdx--) {
var prop = nonEnumerableProps[nonEnumIdx];
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
keys.push(prop);
}
}
}
return keys;
};
本文标签: How to list the properties of a JavaScript objectStack Overflow
版权声明:本文标题:How to list the properties of a JavaScript object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736671772a1946960.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
_.keys(myJSONObject)
– Endy Tjahjono Commented Sep 28, 2013 at 8:44Object.keys(obj)
Sometimes you want non-enumerable properties as well. Make sure to remember this if you do! To get them, useObject.getOwnPropertyNames(obj)
stackoverflow.com/a/32413145/1599699 – Andrew Commented Jun 17, 2020 at 1:12