gpt4 book ai didi

javascript - 根据内容提取对象数组

转载 作者:行者123 更新时间:2023-11-30 08:41:08 25 4
gpt4 key购买 nike

在 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]);
}
}

最佳答案

最后总会通过内部循环来解决,例如

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

关于javascript - 根据内容提取对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26276767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com