1

I have the following javascript array:

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?

Doing groupedDataSet[0].length doesn't work.

Thanks.

Nitzan Wilnai
  • 923
  • 9
  • 24

2 Answers2

3
Object.keys(groupedDataSet[0]).length

should get you what you're looking for. It returns an array containing the instance keys in the object.

Chris Tavares
  • 29,165
  • 4
  • 46
  • 63
  • Once I have the key saved in a variable, how do I access the value? For example key = Object.keys(groupedDataSet[0]). How do I use key to get the actual value stored in groupedDataSet[0]. ? – Nitzan Wilnai Sep 03 '13 at 17:27
  • 1
    Figured it out. Object.keys(groupedDataSet[0])[key] will return me the value. Thanks! – Nitzan Wilnai Sep 03 '13 at 17:39
1

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"] 
zs2020
  • 53,766
  • 29
  • 154
  • 219