6
 var legend=[{"min":0,
            "max":first_color,
            "color":"#1a9850"
  },
  {
      "min":first_color,
      "max":sec_color,
      "color":"#fee08b"
  },
  {
      "min":sec_color,
      "max":thrd_color,
      "color":"#ff3300"
  },
  {
      "min":thrd_color,
      "max":frth_color,
      "color":"#d73027"
      "Abc":"gsfg"
  }

  ];

I'd like to find out each object's property count. E.g. the first 3 objects have 3 properties and 4th one has 4 props, etc.

Roland
  • 9,321
  • 17
  • 79
  • 135
Gaurav Singh
  • 343
  • 1
  • 3
  • 11
  • 1
    That's not JSON; that's a JavaScript array. – Biffen Nov 16 '16 at 06:07
  • 1. Iterate 2. Get current element in array 3. `Object.keys(arrayEl).length` – Tushar Nov 16 '16 at 06:07
  • can you post your code coz m new in js – Gaurav Singh Nov 16 '16 at 06:08
  • 1
    What does "coz m" mean? –  Nov 16 '16 at 06:11
  • 1
    Where are you stuck? Are you having a problem looping over the elements/objects in the array? Are you having a problem getting the list of each object's keys? –  Nov 16 '16 at 06:11
  • Objects don't have "lengths". They have some number of properties. –  Nov 16 '16 at 06:15
  • Currently you have an array of Objects so 1. iterating over the array: `for(var i = 0; i < legend.length; i++) { // Code that does something with each object here}` 2. find how many keys in that particular object - `Object.keys(legend[i]),length` OR iterate over each key and do something with it `for(var key in legend[i]){ console.log(legend[i][key]) }` 3. make it more readable - within 1. you could do `var currentLegend = legend[i];` then use that instead in 2. especially if you need to do more than just count the keys – Brian Nov 16 '16 at 06:21

3 Answers3

11

Iterate over the array and get object property names count.

var legend = [{
  "min": 0,
  "max": 'first_color',
  "color": "#1a9850"
}, {
  "min": 'first_color',
  "max": 'sec_color',
  "color": "#fee08b"
}, {
  "min": 'sec_color',
  "max": 'thrd_color',
  "color": "#ff3300"
}, {
  "min": 'thrd_color',
  "max": 'frth_color',
  "color": "#d73027",
  "Abc": "gsfg"
}];

var res = legend.map(function(v) {
  console.log(Object.keys(v).length);
  return Object.keys(v).length;
});

console.log(res);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
7

But a better solution would be to prototype Object

Object.size = function(obj) {
   return Object.keys(obj).length;
}
Community
  • 1
  • 1
Amit
  • 5,924
  • 7
  • 46
  • 94
4

you can use Object.keys

 console.log(Object.keys(legend[0]).length)// 3

 console.log(Object.keys(legend[3]).length);//4
Deep
  • 9,594
  • 2
  • 21
  • 33