2014-10-22 95 views
0

我有一個對象在JavaScript:jQuery - 如何在對象內的數組內找到特定的JavaScript對象?

var stuffObject = { 
    stuffArray1 : [object1, object2, object3], 
    stuffArray2 : [object4, object5, object6] 
} 

object1到6這個樣子的:

object1 = { 
    dataStuff : { 
     stuffId: "foobar" 
    } 
} 

我的問題:給定的關鍵 「FOOBAR」,如何從使用jQuery的stuffObject檢索object1 ?關鍵的「stuffId」總是具有獨特的價值。

回答

0

感謝您的幫助球員,用別人的輸入我已經解決了它自己:

getStuffById: function(id){ 
    for (stuffArray in stuffObject) { 
      for (stuff in stuffObject[stuffArray]) { 
       if (stuffObject[stuffArray][stuff].dataStuff.stuffId == id) { 
        return stuffObject[stuffArray][stuff]; 
       } 
      } 
     } 
    return null; 
} 

這也適用於比使用.grep()的(現已刪除)回答更好,因爲這個函數一找到正確的對象就立即終止。

1

您不會繞過該集合來查找您正在查找的對象。 jQuery不能真正幫助。它的目的是DOM操作。如果您想要處理對象,設置,列表等功能,請查看lodash

我寫了一個函數來處理這個問題。我希望這是可以理解的。

var stuffObject = { 
    stuffArray1 : [{dataStuff: {stuffId: 'foobar'}}, {dataStuff: {stuffId: 'foo'}}, {}], 
    stuffArray2 : [{}, {dataStuff: {stuffId: 'bar'}}, {}] 
} 

function getObjByStuffId(stuffObject, stuffId) { 
    var key, arr, i, obj; 
    // Iterate over all the arrays in the object 
    for(key in stuffObject) { 
     if(stuffObject.hasOwnProperty(key)) { 
      arr = stuffObject[key]; 
      // Iterate over all the values in the array 
      for(i = 0; i < arr.length; i++) { 
       obj = arr[i]; 
       // And if it has the value we are looking for 
       if(typeof obj.dataStuff === 'object' 
        && obj.dataStuff.stuffId === stuffId) { 
        // Stop searching and return the object. 
        return obj; 
       } 
      } 
     } 
    } 
} 

console.log('foobar?', getObjByStuffId(stuffObject, 'foobar')); 
console.log('foo?', getObjByStuffId(stuffObject, 'foo')); 
console.log('bar?', getObjByStuffId(stuffObject, 'bar')); 
相關問題