如何拿到对象中键值对的键名

    技术2022-07-11  124

    如何拿到对象中键值对的键名

    I adore JavaScript objects.  Love them.  You're probably asking "well, why don't you marry them?"  Trust me:  if I could, I would.  Arrays are nice and all but object keys provide another level of structure and information that is invaluable.  For example, it's much faster search an object for a key than it is to search an array for value presence.

    我喜欢JavaScript对象。 爱他们。 您可能会问:“恩,为什么不嫁给他们?” 相信我:如果可以的话,我会的。 数组很不错,除了对象键之外的所有键都提供了另​​一层宝贵的结构和信息。 例如,在对象中搜索键要比在数组中搜索值存在快得多。

    The way we've always iterated on an Object instance was always a for loops with a hasOwnProperty check which was ugly; Object.keys (not Object.prototype.keys) provides an array of Object properties!

    我们一直在Object实例上进行迭代的方式始终是使用hasOwnProperty检查的for循环,这很丑陋。 Object.keys (不是Object.prototype.keys )提供了一个Object属性数组!

    var person = { firstName: 'David', lastName: 'Walsh', // ... }; Object.keys(person).forEach(function(trait) { console.log('Person ', trait,': ', person[trait]); });

    If you work with JSON or simply raw JavaScript objects, and you haven't been using Object.keys, now is the time to ditch the old method for this elegant solution!

    如果您使用JSON或仅使用原始JavaScript对象,并且还没有使用过Object.keys ,那么现在该放弃这种优雅解决方案的旧方法了!

    翻译自: https://davidwalsh.name/object-keys

    如何拿到对象中键值对的键名

    Processed: 0.321, SQL: 9