简体   繁体   English

在 JavaScript 中获取对象的所有属性

[英]Getting all the properties of an object in JavaScript

Does JavaScript have a way to get all the properties of an object, including the built-in ones? JavaScript 有办法获取对象的所有属性,包括内置属性吗? for... in skips built-in properties, which is usually what you want, but not in this case. for... in跳过内置属性,这通常是您想要的,但在这种情况下不是。 I'm using Node.js if that matters, and it's for debugging purposes so it doesn't have to be elegant, fast or portable.如果这很重要,我正在使用 Node.js,它用于调试目的,因此它不必是优雅的、快速的或可移植的。

Yeah it does, just go up through the prototype and get all properties是的,只是通过原型并获得所有属性

function getAllProperties(o) {
    var properties = [];
    while (o) {
        [].push.apply(properties, Object.getOwnPropertyNames(o))
        o = Object.getPrototypeOf(o);
    }
    //remove duplicate properties
    properties = properties.filter(function(value, index) {
        return properties.indexOf(value) == index;
    })
    return properties;
}

Well, for debug you could use this:好吧,对于调试,你可以使用这个:

console.log(yourObject);

Simple and fast.简单快速。 Both in node and in browser.在节点和浏览器中。 : ) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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