在对象在Javascript数组查找值 [英] Find a value in an array of objects in Javascript
本文介绍了在对象在Javascript数组查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道类似的问题已经被问过,但是这一次是有点不同。我有不愿透露姓名的对象,它包含一个名为对象的数组的数组,我需要得到其中的名是字符串1的对象。下面是一个例子阵列。
I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array.
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
更新:我应该说这个较早,但一旦我找到它,我想与编辑的对象来代替它。
Update: I should have said this earlier, but once I find it, I want to replace it with an edited object.
推荐答案
您可以循环数组和测试该属性在:
You can loop over the array and test for that property:
function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
var resultObject = search("string 1", array);
这篇关于在对象在Javascript数组查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文