2014-09-30 57 views
0

我有這個陣列創造價值形式arryay Jquery?

var activeId = 1; 

var getAll = [{ 
    "id": "1", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}, { 
    "id": "2", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}] 

我需要的是與activeId = 1來獲得唯一成員,並且不是創建新的變種,我可以提醒?

嘗試過這樣的事情,但我沒有運氣?

$.each(getAll, function(_, val) { 
    if (val.id == activeId) { 
     name = val.name; 
     position = val.position; 
     office = val.office; 
    } 
}); 

alert(position); 
+0

的警報沒有顯示。 – 2014-09-30 12:09:35

+0

它顯示,但在所有名稱,位置,辦公室我得到了相同的結果? – Schneider 2014-09-30 12:11:12

回答

1

您可以使用​​功能。

var activeId = 1; 
 

 
var getAll = [{ 
 
    "id": "1", 
 
    "name": "John", 
 
    "position": "CEo", 
 
    "office": "NY", 
 
    "active": "Yes" 
 

 
}, { 
 
    "id": "2", 
 
    "name": "John", 
 
    "position": "CEowe", 
 
    "office": "NY", 
 
    "active": "Yes" 
 

 
}]; 
 

 
var filtered = jQuery.grep(getAll, function(n, i) { 
 
    return (n.id == activeId); 
 
}); 
 

 
for (var item in filtered) { 
 
    document.write("Id:" + filtered[item].id + " Name:" + filtered[item].name + " position:" + filtered[item].position); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

0

請更新您的陣列

VAR activeId = 1;

var getAll = [{ 
    "id": "1", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}, { 
    "id": "2", 
    "name": "Austin", 
    "position": "Manager", 
    "office": "US", 
    "active": "Yes" 

}] 
0

你應該聲明變量循環:)外

http://jsfiddle.net/gwwtukha/3/

var name, position, office; 

$.each(getAll, function (_, val) { 
if (val.id == activeId) { 
    name = val.name; 
    position = val.position; 
    office = val.office; 
    //alert(position); 
} 
}); 
alert(position); 
+0

但是如何在主要作用域中聲明該var? – Schneider 2014-09-30 12:15:12

+0

我已經做了修改,檢查編輯的答案:) – 2014-09-30 12:15:31

0

試試這個:

var getAll = [{ 
    "id": "1", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}, { 
    "id": "2", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 
}]; 

getAll = $.map(getAll, function (item) { 
    return (item['active'] === 'Yes'? item : null); 
}); 

這會給你與兩個對象的數組,你不能提醒這些用戶,你必須使它們成爲一種格式警報,可以處理如嚴格G:

getAll = JSON.stringify(getAll); 
alert(getAll); 

但你可以隨時檢查檢查員工具的項目,如果您打印到控制檯,像這樣:

console.log(getAll);