本文翻译自:Find a value in an array of objects in Javascript [duplicate]
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". 我有一个未命名对象的数组,其中包含一个已命名对象的数组,我需要获取“名称”为“字符串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. 更新:我应该早先说过,但是一旦找到它,我想用一个编辑过的对象替换它。
#1楼
参考:https://stackoom.com/question/qI18/在Javascript对象数组中查找值-重复
#2楼
You can do it with a simple loop: 您可以通过一个简单的循环来做到这一点:
var obj = null;
for (var i = 0; i < array.length; i++) {
if (array[i].name == "string 1") {
obj = array[i];
break;
}
}
#3楼
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);
#4楼
Either use a simple for
-loop: 使用一个简单的for
循环:
var result = null;
for (var i = 0; i < array.length; i++) {
if (array[i].name === "string 1") {
result = array[i];
break;
}
}
Or if you can, that is, if your browser supports it, use Array.filter
, which is much more terse: 或者,如果可以的话,也就是说,如果您的浏览器支持它,请使用Array.filter
,它更简洁:
var result = array.filter(function (obj) {
return obj.name === "string 1";
})[0];
#5楼
Finding the array element: 查找数组元素:
let arr = [ { name:"string 1", value:"this", other: "that" }, { name:"string 2", value:"this", other: "that" } ]; let obj = arr.find(o => o.name === 'string 1'); console.log(obj);
Replacing the array element: 替换数组元素:
let arr = [ { name:"string 1", value:"this", other: "that" }, { name:"string 2", value:"this", other: "that" } ]; let obj = arr.find((o, i) => { if (o.name === 'string 1') { arr[i] = { name: 'new string', value: 'this', other: 'that' }; return true; // stop searching } }); console.log(arr);
#6楼
Here is the solution for search and replace 这是搜索和替换的解决方案
function searchAndUpdate(name,replace){
var obj = array.filter(function ( obj ) {
return obj.name === name;
})[0];
obj.name = replace;
}
searchAndUpdate("string 2","New String 2");