简体   繁体   English

从对象数组获取键值

[英]Getting key values from an array of objects

I am trying to extract the names of all keys from an array of objects keeping time complexity as n(One loop only). 我试图从保持时间复杂度为n(仅一个循环)的对象数组中提取所有键的名称。 The array is as below: 数组如下:

var addressArray = [{"city":"New York"},{"country":"USA"},{"zip": 45677}];

I want to extract the below: 我想提取以下内容:

var addressKeys = ["city", "country", "zip"].

I am able to do the same by first looping through the array and then using a key in obj loop but that doesn't loo good. 我能够通过首先遍历数组然后在obj循环中使用键来做到这一点,但这并不好。 Alternatives are most welcome. 我们欢迎其他选择。

Use Object.keys to get the keys. 使用Object.keys获取密钥。

if (typeof Object.keys !== "function") {
    (function() {
        Object.keys = Object_keys;
        function Object_keys(objectToGet) {
            var keys = [], name;
            for (name in objectToGet) {
                if (objectToGet.hasOwnProperty(name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

From your definition addressArray is an object not an array. 根据您的定义, addressArray是一个对象而不是数组。

You can use Object.keys() to get the keys array of an object. 您可以使用Object.keys()获取对象的keys数组。

var addressKeys = Object.keys(addressArray);

To support older browsers , which does not support Object.keys you can use a Polyfill 要支持不支持Object.keys 旧版浏览器 ,可以使用Polyfill

Use for-in loop to access each key-value pair and then push to new array: (Recommended) 使用for-in循环访问每个key-value对,然后推送到新数组:( 推荐)

for(var index in addressArray){
    addressKeys.push(index)
}

Another solution is: 另一个解决方案是:

var addressKeys = Object.keys(addressArray)

which is slower comparatively. 比较慢。

Note that I switched []'s with {}'s: 请注意,我用{}切换了[]的位置:

var addressObject = {"city":"New York", "country":"USA", "zip": 45677};

var keys = [];

for(var address in addressObject)
{
    keys.push(address);
}

console.log(keys);

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

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