![](/img/trans.png)
[英]How to loop through two arrays and find common value object? Javascript using forEach
[英]Loop through two arrays in Javascript to search an object by value
我正在嘗試遍歷兩個數組,以從第一個數組中找到一個與第二個數組中的數字匹配的id。 現在,我得到一個無限循環(wheeee!)或整個第一個數組。 當我對ID號進行硬編碼時,它會返回我想要的組織。 順便說一下,我編寫了一些簡單的數據來處理循環。
碼:
var clients = [{
"id": 1,
"organization": "Sir Barks a lot"
},
{
"id": 2,
"organization": "Wag the dog daycare"
},
{
"id": 3,
"organization": "Purfect pet sitters"
}
];
var index = [1, 7, 8];
var orgName = [];
for (var i = 0; i < clients.length; i++) {
for (var y = 0; y <= index.length; y++) {
if (clients[i].id == [y]) {
orgName.push(clients[i].organization);
}
}
}
console.log(orgName);
您的比較中有一個錯誤:
`clients[i].id === [y]` should be `clients[i].id === index[y]`
var clients = [{"id":1,"organization":"Sir Barks a lot"},{"id":2,"organization":"Wag the dog daycare"},{"id":3,"organization":"Purfect pet sitters"}]; var index = [1, 7, 8]; var orgName = []; for (var i = 0; i < clients.length; i++) { for (var y = 0; y < index.length; y++) { if (clients[i].id === index[y]) { // you need to compare it to the index in the y place, and not to y or [y] orgName.push(clients[i].organization); } } } console.log(orgName);
另一種方法是使用Array#reduce從第一個數組創建對象圖,然后Array#reduce第二個數組,並從對象圖獲取值:
var clients = [{"id":1,"organization":"Sir Barks a lot"},{"id":2,"organization":"Wag the dog daycare"},{"id":3,"organization":"Purfect pet sitters"}]; var index = [1, 7, 8]; var clientsMap = clients.reduce(function(m, o) { m[o.id] = o; return m; }, Object.create(null)); var result = index.reduce(function(r, i) { clientsMap[i] && r.push(clientsMap[i].organization); return r; }, []); console.log(result);
Matt給出了最簡單的答案,當我想起要獲取索引時,上述方法非常有用。
if(clients [i] .id == index [y])而不是if(clients [i] .id == [y])
我對您的代碼做了兩個簡單的更改,這些更改導致了您的錯誤。
for (var y = 0; y < index.length; y++) {
在遍歷數組時,您希望將循環從0迭代到array-1的長度(也稱為0到您的array Exclusive的長度)。 這是一種非常常見的做法,將有助於減少代碼中的一個錯誤。
if (clients[i].id == index[y])
在您的代碼中,您正在將y的值與數組中位置“ i”的客戶端ID進行比較。 您要做的是比較數組中'y'位置的index值 。 否則,您只是在檢查clients [i] .id是否等於0、1、2等。
var clients = [{
"id": 1,
"organization": "Sir Barks a lot"
},
{
"id": 7,
"organization": "Wag the dog daycare"
},
{
"id": 3,
"organization": "Purfect pet sitters"
}
];
var index = [1, 7, 8];
var orgName = [];
for (var i = 0; i < clients.length; i++) {
for (var y = 0; y < index.length; y++) {
if (clients[i].id == index[y]) {
orgName.push(clients[i].organization);
}
}
}
window.alert(orgName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.