如何只获取Array类型的键

时间:2017-05-17 13:25:00

标签: jquery angularjs underscore.js

我正在使用带有下划线JS的Angular JS 我有一个如上所示的JSON,从上面的JSON,我试图获取所有类型数组的键。

[{
        "_id": "591c2748f6d215203ee12241",
        "LineSystemOid": "{00033457-0000-0000-F306-D0D1B64F1D04}",
        "LineName": "P-10148",
        "Filter1": [{
            "Reason_1": 1,
            "ReasonShrtStrngVal": "Working",
            "ReasonLngStrngVal": "Working"
        }],
        "Filter2": [{
            "Status_1": 1,
            "StatusShrtStrngVal": "Working",
            "StatusLngStrngVal": "Working"
        }],
        "DateCreated": "2012-05-18 22:54:18.637",
        "DateLastModified": "2014-05-15 22:43:27.533",
        "Filter3": [{
            "CorrelationStatus_1": null,
            "CorrelationStatusShrtStrngVal": null,
            "CorrelationStatusLngStrngVal": null
        }]

    }]

表示我需要的输出是Filter1, Filter2 and Filter3

我试过如下,但我得到的输出是

var allkeys = _.keys(reasons[0]);
console.log(JSON.stringify(allkeys));

输出:

["_id","LineSystemOid","LineName","Filter1","Filter2","DateCreated","DateLastModified"]

我的小提琴

http://jsfiddle.net/vEDcx/10/

3 个答案:

答案 0 :(得分:1)

我的解决方案 - http://jsfiddle.net/d226aco7/

var reasons =  [{
    "_id": "591c2748f6d215203ee12241",
    "LineSystemOid": "{00033457-0000-0000-F306-D0D1B64F1D04}",
    "LineName": "P-10148",
    "Filter1": [{
        "Reason_1": 1,
        "ReasonShrtStrngVal": "Working",
        "ReasonLngStrngVal": "Working"
    }],
    "Filter2": [{
        "Status_1": 1,
        "StatusShrtStrngVal": "Working",
        "StatusLngStrngVal": "Working"
    }],
    "DateCreated": "2012-05-18 22:54:18.637",
    "DateLastModified": "2014-05-15 22:43:27.533",
    "Filter2": [{
        "CorrelationStatus_1": null,
        "CorrelationStatusShrtStrngVal": null,
        "CorrelationStatusLngStrngVal": null
    }]

}]

var allkeys = [];
_.forEach(reasons[0], function(value, key) {
    if (_.isArray(value)) {
    allkeys.push(key);
  }
});

console.log(JSON.stringify(allkeys));

答案 1 :(得分:1)

这是一个使用pickBy获取数组属性然后使用keys获取密钥的解决方案:

let result = _(data[0])
    .pickBy(_.isArray)
    .keys()
    .value();

或没有链接:

let result = _.keys( _.pickBy(data[0], _.isArray));

答案 2 :(得分:0)

尝试使用instanceof运算符并将其检查为Array。它应该是这样的

for(var key in reasons[0])
{
  if(reasons[0][key] instanceof Array)
    {
      console.log(key);
    }
 }