![](/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.