按属性值从对象数组中获取 JavaScript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13964155/
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
Get JavaScript object from array of objects by value of property
提问by user765368
Let's say I have an array of four objects:
假设我有一个包含四个对象的数组:
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
Is there a way that I can get the third object ({a: 5, b: 6}) by the value of the property bfor example without a for...inloop?
有没有办法可以{a: 5, b: 6}通过属性的值获取第三个对象()b,例如没有for...in循环?
回答by elclanrs
Filterarray of objects, which property matches value, returns array:
Filter属性匹配值的对象数组返回数组:
var result = jsObjects.filter(obj => {
return obj.b === 6
})
See the MDN Docs on Array.prototype.filter()
请参阅有关 Array.prototype.filter()的MDN 文档
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
]
let result = jsObjects.filter(obj => {
return obj.b === 6
})
console.log(result)
Findthe value of the first element/object in the array, otherwise undefinedis returned.
Find数组中第一个元素/对象的值,否则undefined返回。
var result = jsObjects.find(obj => {
return obj.b === 6
})
See the MDN Docs on Array.prototype.find()
请参阅Array.prototype.find() 上的MDN 文档
const jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
]
let result = jsObjects.find(obj => {
return obj.b === 6
})
console.log(result)
回答by Micha? Per?akowski
jsObjects.find(x => x.b === 6)
From MDN:
来自 MDN:
The
find()method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefinedis returned.
find()如果数组中的元素满足提供的测试函数,则该方法返回数组中的值。否则undefined返回。
Side note: methods like find()and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel.
旁注:find()较旧的浏览器(如 IE)不支持像和箭头函数这样的方法,所以如果你想支持这些浏览器,你应该使用Babel转译你的代码。
回答by RobG
I don't know why you are against a for loop (presumably you meant a for loop, not specifically for..in), they are fast and easy to read. Anyhow, here's some options.
我不知道你为什么反对 for 循环(大概你的意思是 for 循环,而不是专门 for..in),它们快速且易于阅读。无论如何,这里有一些选择。
For loop:
For循环:
function getByValue(arr, value) {
for (var i=0, iLen=arr.length; i<iLen; i++) {
if (arr[i].b == value) return arr[i];
}
}
.filter
。筛选
function getByValue2(arr, value) {
var result = arr.filter(function(o){return o.b == value;} );
return result? result[0] : null; // or undefined
}
.forEach
.forEach
function getByValue3(arr, value) {
var result = [];
arr.forEach(function(o){if (o.b == value) result.push(o);} );
return result? result[0] : null; // or undefined
}
If, on the other hand you really did mean for..in and want to find an object with any property with a value of 6, then you must use for..in unless you pass the names to check. e.g.
另一方面,如果您确实是指 for..in 并且想要查找具有值为 6 的任何属性的对象,那么您必须使用 for..in 除非您通过名称进行检查。例如
function getByValue4(arr, value) {
var o;
for (var i=0, iLen=arr.length; i<iLen; i++) {
o = arr[i];
for (var p in o) {
if (o.hasOwnProperty(p) && o[p] == value) {
return o;
}
}
}
}
回答by Rohit Jindal
Try Array filtermethod for filter the array of objectswith property.
尝试使用Array 过滤器方法过滤array of objectswith property。
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
using array filter method:
使用数组过滤方法:
var filterObj = jsObjects.filter(function(e) {
return e.b == 6;
});
using for in loop :
使用 for 循环:
for (var i in jsObjects) {
if (jsObjects[i].b == 6) {
console.log(jsObjects[i]); // {a: 5, b: 6}
}
}
Working fiddle :https://jsfiddle.net/uq9n9g77/
工作小提琴:https : //jsfiddle.net/uq9n9g77/
回答by Alireza
OK,there are few ways to do that, but let's start with the simplest one and latest approach to do this, this function is called find().
好的,有几种方法可以做到这一点,但让我们从最简单和最新的方法开始,这个函数被称为find()。
Just be careful when you using findto as even IE11 dosn't support it, so it needs to be transpiled...
使用时要小心find,因为即使 IE11 也不支持它,因此需要对其进行编译...
so you have this object as you said:
所以你有这个对象,正如你所说:
var jsObjects = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6},
{a: 7, b: 8}
];
and you can write a function and get it like this:
你可以编写一个函数并像这样得到它:
function filterValue(obj, key, value) {
return obj.find(function(v){ return v[key] === value});
}
and use the function like this:
并使用这样的功能:
filterValue(jsObjects, "b", 6); //{a: 5, b: 6}
Also in ES6for even shortened version:
同样在ES6中甚至缩短版本:
const filterValue = (obj, key, value)=> obj.find(v => v[key] === value);
This method only return the first value which match..., for better result and browser support, you can use filter:
此方法只返回匹配的第一个值...,为了更好的结果和浏览器支持,您可以使用filter:
const filterValue = (obj, key, value)=> obj.filter(v => v[key] === value);
and we will return [{a: 5, b: 6}]...
我们会回来[{a: 5, b: 6}]...
This method will return an array instead...
此方法将返回一个数组而不是...
You simpley use for loop as well, create a function like this:
您也可以简单地使用 for 循环,创建一个这样的函数:
function filteredArray(arr, key, value) {
const newArray = [];
for(i=0, l=arr.length; i<l; i++) {
if(arr[i][key] === value) {
newArray.push(arr[i]);
}
}
return newArray;
}
and call it like this:
并这样称呼它:
filteredArray(jsObjects, "b", 6); //[{a: 5, b: 6}]
回答by maia
Using underscore.js:
使用 underscore.js:
var foundObject = _.findWhere(jsObjects, {b: 6});
回答by Amir
It looks like in the ECMAScript 6 proposal there are the Arraymethods find()and findIndex(). MDN also offers polyfills which you can include to get the functionality of these across all browsers.
看起来在 ECMAScript 6 提案中有Array方法find()和findIndex(). MDN 还提供了 polyfill,您可以将其包含在内以在所有浏览器中获得这些功能。
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].find(isPrime) ); // undefined, not found
console.log( [4, 5, 8, 12].find(isPrime) ); // 5
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].findIndex(isPrime) ); // -1, not found
console.log( [4, 6, 7, 12].findIndex(isPrime) ); // 2
回答by nickf
If I understand correctly, you want to find the object in the array whose bproperty is 6?
如果我理解正确,您想在数组中找到b属性为6?
var found;
jsObjects.some(function (obj) {
if (obj.b === 6) {
found = obj;
return true;
}
});
Or if you were using underscore:
或者,如果您使用下划线:
var found = _.select(jsObjects, function (obj) {
return obj.b === 6;
});
回答by Sam Dushay
If you are looking for a single result, rather than an array, may I suggest reduce?
如果您正在寻找单个结果而不是数组,我可以建议减少吗?
Here is a solution in plain 'ole javascript that returns a matching object if one exists, or null if not.
这是一个简单的 'ole javascript 解决方案,如果存在则返回匹配对象,否则返回 null。
var result = arr.reduce(function(prev, curr) { return (curr.b === 6) ? curr : prev; }, null);
回答by Shobhit Sharma
You can use it with the arrow function as well like as below :
您可以将它与箭头功能一起使用,如下所示:
var demoArray = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
var result = demoArray.filter( obj => obj.name === 'apples')[0];
console.log(result);
// {name: 'apples', quantity: 2}

