使用 underscore.js 在对象数组中查找对象

问题描述 投票:0回答:2

我有以下结构

var myArr = [ {Code: 'UY', Name: "testdfdgf"}];

我需要从代码='UY'的数组中提取一个对象。

使用 _underscore.js 的正确方法是什么? (我不想遍历数组)。

javascript search underscore.js
2个回答
3
投票

来自 underscorejs.org

findWhere_.findWhere(list, properties) 遍历列表并 返回与列出的所有键值对匹配的第一个值 在属性中。

如果找不到匹配项,或者如果列表为空,将返回 undefined。

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"}); => {year: 1918, newsroom: "The New York Times", reason: "为了公共服务,完整地发布了这么多官方报告,
欧洲政治家有关进展的文件和讲话 和战争的进行。”}

所以本质上:

var codeUY = _.findWhere(myArr, {Code: 'UY'});

Underscore 会遍历你的数组来找到这个,我不认为你可以绕过它,这应该在第一次匹配时停止;


0
投票

使用filter函数,如果你想要多个对象代码:UY,或find函数来获取第一个对象。

© www.soinside.com 2019 - 2024. All rights reserved.