[英]jQuery - how to find a specific JavaScript object inside an array within an object?
我在javaScript中有一個對象:
var stuffObject = {
stuffArray1 : [object1, object2, object3],
stuffArray2 : [object4, object5, object6]
}
object1到6看起來像這樣:
object1 = {
dataStuff : {
stuffId: "foobar"
}
}
我的問題:給定鍵“ foobar”,如何使用jQuery從stuffObject檢索object1? 鍵“ stuffId”始終具有唯一值。
您將無法遍歷集合以查找所需的對象。 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') );
感謝您的幫助,利用其他人的幫助,我自己解決了這個問題:
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()的答案(現在已刪除)更好,因為此函數在找到正確的對象后立即終止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.