【问题标题】:Return JSON properties返回 JSON 属性
【发布时间】:2016-01-26 22:47:55
【问题描述】:

我正在尝试返回我的 JSON 对象的属性。我的 JSON 文件对象如下所示:

{ Products: 
   { 
     'Cars': { tableFields: [Object] },
     'Planes': { tableFields: [Object] } 
   } 
}

我正在尝试返回一个包含 Products' 属性的数组 - CarsPlanes。例如 - 我希望最终结果是以下数组:

['Cars', 'Planes']

有人可以帮忙吗?

谢谢!

【问题讨论】:

    标签: javascript json object properties key


    【解决方案1】:

    你可以使用Object.keys()函数:

    var data = {
        Products: {
            'Cars': {
                tableFields: [ Object ]
            },
            'Planes': {
                tableFields: [ Object ]
            }
        }
    };
    
    var result = Object.keys(data.Products);
    console.log(result);
    

    【讨论】:

      【解决方案2】:
      var keys = [];
      for ( var key in Products )
      {
          //We only want the direct properties
          if ( Products.hasOwnProperty( key ) ) keys[ keys.length ] = key;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-30
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 2021-11-18
        • 2018-04-06
        相关资源
        最近更新 更多