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.

7
  • 1
    That's not JSON; that's a JavaScript array. Commented Nov 16, 2016 at 6:07
  • 1. Iterate 2. Get current element in array 3. Object.keys(arrayEl).length Commented Nov 16, 2016 at 6:07
  • can you post your code coz m new in js Commented Nov 16, 2016 at 6:08
  • 1
    What does "coz m" mean? Commented Nov 16, 2016 at 6: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? Commented Nov 16, 2016 at 6:11

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

6 Comments

I really must remember to use map more +1 for a nice clean solution!
one more silly question what if i want to know which field are persent in json array in first there are min max and color and in fourth one min max color and Abc etc
coz for iterating object we must know key
Object.keys returns an array of keys so you can iterate over that using either map again or a regular for loop.
thx you so much..............
|
7

But a better solution would be to prototype Object

Object.size = function(obj) {
   return Object.keys(obj).length;
}

2 Comments

Why is that a better solution?
@torazaburo Because it would be cleaner for more than 1 usage. Object.size(obj) is simpler and more human readable.
4

you can use Object.keys

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.