在对象数组中查找匹配对象? [英] Finding matching objects in an array of objects?

查看:538
本文介绍了在对象数组中查找匹配对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var set = [{"color":"blue"},{"color":"green"},{"color":"red"},{"color":"green"}];

我希望能够做类似db调用的事情, set.find({color:green})让它返回一个包含该属性的对象数组。

I'd like to be able to do something like a db call, set.find({"color":"green"}) and have it return an array full of objects that contain that property.

推荐答案

使用 Array#filter ,对于这种特殊情况,代码看起来像

Using Array#filter, for this particular case the code would look like

var results = set.filter(function (entry) { return entry.color === "green"; });

数组#filter 未实现较旧的浏览器,因此请查看链接文章以获得向后兼容的垫片,或者更好地获得完整的ES5垫片

Array#filter is not implemented in some older browsers, so see the linked article for a backward compatibility shim, or better yet get a full-fledged ES5 shim.

对于更一般的情况,只需要扩展这个想法:

For the more general case, it's just a matter of extending this idea:

function findByMatchingProperties(set, properties) {
    return set.filter(function (entry) {
        return Object.keys(properties).every(function (key) {
            return entry[key] === properties[key];
        });
    });
}

var results = findByMatchingProperties(set, { color: "green" });

同样,我使用ECMAScript 5方法 Object.keys Array#every ,因此请使用ES5垫片。 (代码在没有ES5垫片的情况下可行,但使用手动循环,写入和读取的乐趣要少得多。)

Again, I am using ECMAScript 5 methods Object.keys and Array#every, so use an ES5 shim. (The code is doable without an ES5 shim but uses manual loops and is much less fun to write and read.)

这篇关于在对象数组中查找匹配对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆