【问题标题】:Using findWhere with nested objects in an array将 findWhere 与数组中的嵌套对象一起使用
【发布时间】:2016-01-04 02:30:06
【问题描述】:

我有一个看起来像这样的数据结构

var foo = [
    {
        bar: {
            something: 123
        },
        baz: {
            somethingElse: 321
        }
    },
    {
        bar: {
            something: 444
        },
        baz: {
            somethingElse: 555
        }
    }
];

然后我有一个变量:

var findMe = 444;

我想搜索我的foo 数据结构(对象数组),看看findMe 是否匹配foo 数组中任何对象的bar.something 属性。

使用 underscore.js,我会认为下面的代码 sn-p 可以解决问题:

var _ = require('underscore');
var thingImLookingFor = _.findWhere(foo, {bar.something: findMe});

但是,这会在我的应用程序中产生语法错误:

Uncaught SyntaxError: Unexpected token .

是否有人能够阐明我如何实现我正在寻找的搜索?

谢谢!

【问题讨论】:

  • 你需要进行深度查找stackoverflow.com/questions/17578725/…
  • 或者你可以试试 JSONPath goessner.net/articles/JsonPath
  • @YarGnawh 感谢您的回复 :) 幸运的是,因为可以确定搜索的深度以及需要搜索的确切键,我可以使用 find()。我不确定该方法对性能的影响,但从我的基准测试来看,它看起来不错:)

标签: javascript underscore.js


【解决方案1】:

找到我的问题的解决方案。

_.find() 很好地完成了我想要的操作。

_.find(foo, function(obj) {
    return obj.bar.something == findMe;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2014-09-13
    • 2020-10-24
    相关资源
    最近更新 更多