Javascript NodeJS 通过键的值在数组中查找对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36259921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS find object in array by value of a key
提问by Ariel Weinberger
I am trying to get an object in an array by the value of one of its keys.
我试图通过其键之一的值获取数组中的对象。
The array:
数组:
var arr = [
{
city: 'Amsterdam',
title: 'This is Amsterdam!'
},
{
city: 'Berlin',
title: 'This is Berlin!'
},
{
city: 'Budapest',
title: 'This is Budapest!'
}
];
I tried doing something like this with lodash
but no success.
我尝试做这样的事情,lodash
但没有成功。
var picked = lodash.pickBy(arr, lodash.isEqual('Amsterdam');
and it returns an empty object.
它返回一个空对象。
Any idea on how I can do this the lodash way (if it's even possible)? I can do it the classic way, creating a new array, looping through all objects and pushing the ones matching my criteria to that new array. But is there a way to do it with lodash?
关于我如何以 lodash 的方式做到这一点的任何想法(如果可能的话)?我可以用经典的方式来做到这一点,创建一个新数组,遍历所有对象并将符合我的条件的对象推送到该新数组。但是有没有办法用 lodash 做到这一点?
This is NOT a duplicate.
这不是重复的。
采纳答案by Joachim Isaksson
Using lodash and an arrow function, it should be as simple as;
使用 lodash 和一个箭头函数,应该很简单;
var picked = lodash.filter(arr, x => x.city === 'Amsterdam');
...or alternately with object notation;
...或交替使用对象符号;
var picked = lodash.filter(arr, { 'city': 'Amsterdam' } );
Note: The above answer used to be based on pickBy
, which as @torazaburo points out below was not a good choice for the use case.
注意:上面的答案曾经基于pickBy
,正如@torazaburo 在下面指出的那样,这对于用例来说不是一个好的选择。
回答by madox2
You can use Array.prototype.find()with pure javascript:
您可以将Array.prototype.find()与纯 javascript 一起使用:
var picked = arr.find(o => o.city === 'Amsterdam');
It is currently not compatiblewith all browsers, you need to check it in your environment (but it should work in NodeJS).
它目前并不与所有浏览器兼容,您需要在您的环境中检查它(但它应该可以在 NodeJS 中工作)。
回答by gurvinder372
classical way is even simpler
经典方式更简单
try
尝试
var output = arr.filter(function(value){ return value.city=="Amsterdam";})
回答by Rajesh
You can use Array.filter
您可以使用 Array.filter
As correctly pointed by @torazaburo, you do not need ternary operator return item[key]?item[key] === value:false
. A simple check return item[key] === value
will do fine.
正如@torazaburo 正确指出的那样,您不需要三元运算符return item[key]?item[key] === value:false
。一个简单的检查return item[key] === value
就可以了。
var arr = [{
city: 'Amsterdam',
title: 'This is Amsterdam!'
}, {
city: 'Berlin',
title: 'This is Berlin!'
}, {
city: 'Budapest',
title: 'This is Budapest!'
}];
Array.prototype.findByValueOfObject = function(key, value) {
return this.filter(function(item) {
return (item[key] === value);
});
}
document.write("<pre>" + JSON.stringify(arr.findByValueOfObject("city", "Amsterdam"), 0, 4) + "</pre>");