根据内容提取对象数组

时间:2014-10-09 11:02:49

标签: javascript json extract

在JavaScript中,我有一个像这样的JSON数组:

var r = [{"name":"a","bool":false},{"name":"b","bool":false},
         {"name":"c","bool":false},{"name":"a","bool":false},
         {"name":"b","bool":false},{"name":"c","bool":true},
         {"name":"a","bool":true}];

我想构建另一个包含所有对象的数组,其中name ==" a"和bool == false。我通过循环解决了这个问题,但我想知道是否有另一种方法可以做到这一点。

我该怎么办?

[编辑] 我的循环是:

var rLen = r.length;
var newArray = [];

for(var i=0;i<rLen;i++) {
    if(r[i].name=="a"&&r[i].bool==false) {
        newArray.push(r[i]);
    }
}

2 个答案:

答案 0 :(得分:4)

最后,它将始终通过内部循环来解决,例如

var r = [{"name":"a","bool":false},{"name":"b","bool":false},
         {"name":"c","bool":false},{"name":"a","bool":false},
         {"name":"b","bool":false},{"name":"c","bool":true},
         {"name":"a","bool":true}];

var result = r.filter(function(item){
    return item.name === 'a' && !item.bool;
});

如果你看一下polyfill,你会注意到循环:

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) { // <-- 
      if (i in t) {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}

由于您对效果感兴趣,因此这里有一个比较两者的jsperf:http://jsperf.com/aarontgrogg-array-filter-vs-for-loop

答案 1 :(得分:1)

可能是

var r1 = r.filter(function(item){ return item.name === "a" && !item.bool; });