简体   繁体   English

如何访问数组中的javascript键/值对

[英]How to access javascript key/value pairs in an array

I have the following javascript array: 我有以下javascript数组:

var groupedDataSet1 = [{year: "0-1k", value1: Math.floor(Math.random()), value2: Math.floor(Math.random()), value3: Math.floor(Math.random())},
            {year: "1-2k", value1: Math.floor(Math.random()), value2: Math.floor(Math.random()), value3: Math.floor(Math.random())},
            {year: "2-3k", value1: Math.floor(Math.random()), value2: Math.floor(Math.random()), value3: Math.floor(Math.random())},
            {year: "3-4k", value1: Math.floor(Math.random()), value2: Math.floor(Math.random()), value3: Math.floor(Math.random())},
            {year: "4-5k", value1: Math.floor(Math.random()), value2: Math.floor(Math.random()), value3: Math.floor(Math.random())}];

I'd like to programatically know how many key/value pairs I have in each entry. 我想以编程方式知道每个条目中有多少个键/值对。

Is there a way to know that groupedDataSet contains the keys year, value1, value2, and value3 while another javascript array might only contain year, value1 and value2? 有没有办法知道groupsDataSet包含键year,value1,value2和value3,而另一个javascript数组可能只包含year,value1和value2?

Doing groupedDataSet[0].length doesn't work. 执行groupedDataSet [0] .length不起作用。

Thanks. 谢谢。

Object.keys(groupedDataSet[0]).length

should get you what you're looking for. 应该得到你想要的东西。 It returns an array containing the instance keys in the object. 它返回一个包含对象中实例键的数组。

If the objects in the list may have different key set, then you have to check each object to collect all keys. 如果列表中的对象可能具有不同的键集,则必须检查每个对象以收集所有键。 You can do 你可以做

var keys_memo = {};
groupedDataSet1.forEach(function (item) {
    for (var i in item) {
        keys_memo[i] = 1;
    }
});
var keys = Object.keys(keys_memo);

console.log(keys)
>>>["year", "value1", "value2", "value3"] 

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

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