This question already has an answer here:
这个问题已经有了答案:
- Find object by id in an array of JavaScript objects 28 answers
- 在JavaScript对象数组中按id查找对象28个答案
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 b
for example without a for...in
loop?
是否有一种方法可以通过属性b的值获得第三个对象({a: 5, b: 6})例如,没有a for…在循环?
18 个解决方案
#1
597
var result = jsObjects.filter(function( obj ) {
return obj.b == 6;
});
See the MDN Docs on Array.prototype.filter()
参见Array.prototype.filter()中的MDN文档。
#2
162
jsObjects.find(x => x.b === 6)
From MDN:
中数:
The
find()
method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefined
is returned.如果数组中的元素满足所提供的测试函数,那么find()方法将返回数组中的一个值。否则将返回未定义。
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()和arrow这样的方法不受旧浏览器(如IE)的支持,所以如果您想要支持这些浏览器,您应该使用Babel来传递代码。
#3
129
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
.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.
另一方面,如果你真的想要…如果要找到一个具有任何属性值为6的对象,则必须使用。除非你把名字传过来检查。如。
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;
}
}
}
}
#4
26
Try Array filter method for filter the array of objects
with 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 :
用于in循环:
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/
#5
19
Using underscore.js:
使用underscore.js:
var foundObject = _.findWhere(jsObjects, {b: 6});
#6
16
It looks like in the ECMAScript 6 proposal there are the Array
methods find()
and findIndex()
. MDN also offers polyfills which you can include to get the functionality of these across all browsers.
看起来在ECMAScript 6提案中有查找()和findIndex()数组方法。MDN还提供了polyfill,您可以通过它在所有浏览器中获得这些功能。
find():
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
findIndex():
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
#7
15
If I understand correctly, you want to find the object in the array whose b
property 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;
});
#8
11
If you are looking for a single result, rather than an array, may I suggest reduce?
如果您正在寻找单个结果,而不是数组,我是否可以建议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);
#9
9
How about using _.find(collection, [predicate=_.identity], [fromIndex=0])
of lo-dash to get object from array of objects by object property value. You could do something like this:
如何使用_。找到(收集、谓语= _。身份],[fromIndex = 0])lo-dash得到对象数组的对象的对象属性值。你可以这样做:
var o = _.find(jsObjects, {'b': 6});
Arguments:
参数:
collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.
Returns
返回
(*): Returns the matched element (in your case, {a: 5, b: 6}), else undefined.
In terms of performance, _.find()
is faster as it only pulls the first object with property {'b': 6}
, on the other hand, if suppose your array contains multiple objects with matching set of properties (key:value), then you should consider using _.filter()
method. So in your case, as your array has a single object with this property, I would use _.find()
.
就性能而言,_.find()更快,因为它只提取具有属性{'b': 6}的第一个对象,另一方面,如果您的数组包含具有匹配属性集(key:value)的多个对象,那么您应该考虑使用_.filter()方法。在你的例子中,由于数组中只有一个对象具有这个属性,我将使用_.find()。
#10
7
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 find
to as even IE11 dosn't support it, so it needs to be transpiled...
在使用find to时要小心,因为即使是IE11 dosn也不支持它,所以它需要传输……
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 ES6 for 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
:
此方法只返回与…匹配的第一个值。,以获得更佳的效果及浏览器支援,你可使用过滤器:
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:
你简单地使用循环,创建一个这样的函数:
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}]
#11
5
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}
#12
4
See this documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
Example :
看到这个文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values的例子:
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
#13
3
Just improved the fastest/best part of this answer to be more re-usable/clear:
只是提高了最快/最佳答案的一部分更可重用/清楚:
function getElByPropVal(arr, prop, val){
for (var i = 0, length = arr.length; i < length; i++) {
if (arr[i][prop] == val){
return arr[i];
}
}
}
#14
2
You can use the Array.filter method: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
可以使用数组。筛选方法:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
#15
1
To get first object from array of objects by a specific property value:
获得第一个对象的数组对象的特定属性值:
function getObjectFromObjectsArrayByPropertyValue(objectsArray, propertyName, propertyValue) {
return objectsArray.find(function (objectsArrayElement) {
return objectsArrayElement[propertyName] == propertyValue;
});
}
function findObject () {
var arrayOfObjectsString = document.getElementById("arrayOfObjects").value,
arrayOfObjects,
propertyName = document.getElementById("propertyName").value,
propertyValue = document.getElementById("propertyValue").value,
preview = document.getElementById("preview"),
searchingObject;
arrayOfObjects = JSON.parse(arrayOfObjectsString);
console.debug(arrayOfObjects);
if(arrayOfObjects && propertyName && propertyValue) {
searchingObject = getObjectFromObjectsArrayByPropertyValue(arrayOfObjects, propertyName, propertyValue);
if(searchingObject) {
preview.innerHTML = JSON.stringify(searchingObject, false, 2);
} else {
preview.innerHTML = "there is no object with property " + propertyName + " = " + propertyValue + " in your array of objects";
}
}
}
pre {
padding: 5px;
border-radius: 4px;
background: #f3f2f2;
}
textarea, button {
width: 100%
}
<fieldset>
<legend>Input Data:</legend>
<label>Put here your array of objects</label>
<textarea rows="7" id="arrayOfObjects">
[
{"a": 1, "b": 2},
{"a": 3, "b": 4},
{"a": 5, "b": 6},
{"a": 7, "b": 8, "c": 157}
]
</textarea>
<hr>
<label>property name: </label> <input type="text" id="propertyName" value="b"/>
<label>property value: </label> <input type="text" id="propertyValue" value=6 />
</fieldset>
<hr>
<button onclick="findObject()">find object in array!</button>
<hr>
<fieldset>
<legend>Searching Result:</legend>
<pre id="preview">click find</pre>
</fieldset>
#16
0
Using find with bind to pass specific key values to a callback function.
使用find和bind将特定的键值传递给回调函数。
function byValue(o) {
return o.a === this.a && o.b === this.b;
};
var result = jsObjects.find(byValue.bind({ a: 5, b: 6 }));
#17
0
var result = jsObjects.filter(x=> x.b === 6);
will be better, using return in filter sometimes you can't get result (I dunno why)
会更好,使用返回过滤器有时不能得到结果(我不知道为什么)
#18
-25
var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];
to access the third object, use: jsObjects[2];
to access the third object b value, use: jsObjects[2].b;
要访问第三个对象,使用:jsObjects[2];要访问第三个对象b值,使用:jsObjects[2].b;
#1
597
var result = jsObjects.filter(function( obj ) {
return obj.b == 6;
});
See the MDN Docs on Array.prototype.filter()
参见Array.prototype.filter()中的MDN文档。
#2
162
jsObjects.find(x => x.b === 6)
From MDN:
中数:
The
find()
method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefined
is returned.如果数组中的元素满足所提供的测试函数,那么find()方法将返回数组中的一个值。否则将返回未定义。
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()和arrow这样的方法不受旧浏览器(如IE)的支持,所以如果您想要支持这些浏览器,您应该使用Babel来传递代码。
#3
129
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
.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.
另一方面,如果你真的想要…如果要找到一个具有任何属性值为6的对象,则必须使用。除非你把名字传过来检查。如。
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;
}
}
}
}
#4
26
Try Array filter method for filter the array of objects
with 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 :
用于in循环:
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/
#5
19
Using underscore.js:
使用underscore.js:
var foundObject = _.findWhere(jsObjects, {b: 6});
#6
16
It looks like in the ECMAScript 6 proposal there are the Array
methods find()
and findIndex()
. MDN also offers polyfills which you can include to get the functionality of these across all browsers.
看起来在ECMAScript 6提案中有查找()和findIndex()数组方法。MDN还提供了polyfill,您可以通过它在所有浏览器中获得这些功能。
find():
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
findIndex():
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
#7
15
If I understand correctly, you want to find the object in the array whose b
property 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;
});
#8
11
If you are looking for a single result, rather than an array, may I suggest reduce?
如果您正在寻找单个结果,而不是数组,我是否可以建议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);
#9
9
How about using _.find(collection, [predicate=_.identity], [fromIndex=0])
of lo-dash to get object from array of objects by object property value. You could do something like this:
如何使用_。找到(收集、谓语= _。身份],[fromIndex = 0])lo-dash得到对象数组的对象的对象属性值。你可以这样做:
var o = _.find(jsObjects, {'b': 6});
Arguments:
参数:
collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.
Returns
返回
(*): Returns the matched element (in your case, {a: 5, b: 6}), else undefined.
In terms of performance, _.find()
is faster as it only pulls the first object with property {'b': 6}
, on the other hand, if suppose your array contains multiple objects with matching set of properties (key:value), then you should consider using _.filter()
method. So in your case, as your array has a single object with this property, I would use _.find()
.
就性能而言,_.find()更快,因为它只提取具有属性{'b': 6}的第一个对象,另一方面,如果您的数组包含具有匹配属性集(key:value)的多个对象,那么您应该考虑使用_.filter()方法。在你的例子中,由于数组中只有一个对象具有这个属性,我将使用_.find()。
#10
7
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 find
to as even IE11 dosn't support it, so it needs to be transpiled...
在使用find to时要小心,因为即使是IE11 dosn也不支持它,所以它需要传输……
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 ES6 for 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
:
此方法只返回与…匹配的第一个值。,以获得更佳的效果及浏览器支援,你可使用过滤器:
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:
你简单地使用循环,创建一个这样的函数:
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}]
#11
5
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}
#12
4
See this documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
Example :
看到这个文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values的例子:
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
#13
3
Just improved the fastest/best part of this answer to be more re-usable/clear:
只是提高了最快/最佳答案的一部分更可重用/清楚:
function getElByPropVal(arr, prop, val){
for (var i = 0, length = arr.length; i < length; i++) {
if (arr[i][prop] == val){
return arr[i];
}
}
}
#14
2
You can use the Array.filter method: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
可以使用数组。筛选方法:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
#15
1
To get first object from array of objects by a specific property value:
获得第一个对象的数组对象的特定属性值:
function getObjectFromObjectsArrayByPropertyValue(objectsArray, propertyName, propertyValue) {
return objectsArray.find(function (objectsArrayElement) {
return objectsArrayElement[propertyName] == propertyValue;
});
}
function findObject () {
var arrayOfObjectsString = document.getElementById("arrayOfObjects").value,
arrayOfObjects,
propertyName = document.getElementById("propertyName").value,
propertyValue = document.getElementById("propertyValue").value,
preview = document.getElementById("preview"),
searchingObject;
arrayOfObjects = JSON.parse(arrayOfObjectsString);
console.debug(arrayOfObjects);
if(arrayOfObjects && propertyName && propertyValue) {
searchingObject = getObjectFromObjectsArrayByPropertyValue(arrayOfObjects, propertyName, propertyValue);
if(searchingObject) {
preview.innerHTML = JSON.stringify(searchingObject, false, 2);
} else {
preview.innerHTML = "there is no object with property " + propertyName + " = " + propertyValue + " in your array of objects";
}
}
}
pre {
padding: 5px;
border-radius: 4px;
background: #f3f2f2;
}
textarea, button {
width: 100%
}
<fieldset>
<legend>Input Data:</legend>
<label>Put here your array of objects</label>
<textarea rows="7" id="arrayOfObjects">
[
{"a": 1, "b": 2},
{"a": 3, "b": 4},
{"a": 5, "b": 6},
{"a": 7, "b": 8, "c": 157}
]
</textarea>
<hr>
<label>property name: </label> <input type="text" id="propertyName" value="b"/>
<label>property value: </label> <input type="text" id="propertyValue" value=6 />
</fieldset>
<hr>
<button onclick="findObject()">find object in array!</button>
<hr>
<fieldset>
<legend>Searching Result:</legend>
<pre id="preview">click find</pre>
</fieldset>
#16
0
Using find with bind to pass specific key values to a callback function.
使用find和bind将特定的键值传递给回调函数。
function byValue(o) {
return o.a === this.a && o.b === this.b;
};
var result = jsObjects.find(byValue.bind({ a: 5, b: 6 }));
#17
0
var result = jsObjects.filter(x=> x.b === 6);
will be better, using return in filter sometimes you can't get result (I dunno why)
会更好,使用返回过滤器有时不能得到结果(我不知道为什么)
#18
-25
var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];
to access the third object, use: jsObjects[2];
to access the third object b value, use: jsObjects[2].b;
要访问第三个对象,使用:jsObjects[2];要访问第三个对象b值,使用:jsObjects[2].b;