在Javascript對象數組中查找值[重複]

本文翻譯自:Find a value in an array of objects in Javascript [duplicate]

This question already has answers here : 這個問題已經在這裏有了答案
Closed last year . 去年關閉。

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");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章