Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the length of a JSON object [duplicate]

 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.

like image 726
Gaurav Singh Avatar asked Nov 16 '16 06:11

Gaurav Singh


1 Answers

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);
like image 103
Pranav C Balan Avatar answered Oct 08 '22 13:10

Pranav C Balan