How to find the length of a JSON object

This question already has an answer here:

  • Length of a JavaScript object 32 answers

  • 遍历数组并获取对象属性名称。

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

  • 'JSON' object is the wrong terminology.
  • Referring to 'Length of a JavaScript object', the best solution would be:

    Object.keys(obj).length

  • But a better solution would be to prototype Object

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

    你可以使用Object.keys

     console.log(Object.keys(legend[0]).length)// 3
    
     console.log(Object.keys(legend[3]).length);//4
    
    链接地址: http://www.djcxy.com/p/27262.html

    上一篇: 使用JavaScript进行JSON解析的最佳方法

    下一篇: 如何找到JSON对象的长度