在Javascript中循环遍历两个数组以按值搜索对象

时间:2017-09-22 16:31:59

标签: javascript arrays loops

我正在尝试遍历两个数组以从第一个中找到与第二个数字匹配的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);

3 个答案:

答案 0 :(得分:0)

您的比较中出现错误:

`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);

答案 1 :(得分:0)

Matt有最简单的答案,当我记得我正试图获得y指数时,上述工作很有用。

if(clients [i] .id == index [y])而不是 if(clients [i] .id == [y])

答案 2 :(得分:0)

我对您的代码进行了两次简单的更改,导致您出错。

for (var y = 0; y < index.length; y++) {

循环遍历数组时,您希望将循环从0迭代到数组-1的长度(也称为0到数组的长度独占)。这是一种非常常见的做法,有助于缓解代码中的一个错误。

if (clients[i].id == index[y])

在您的代码中,您要将 y 的值与位置&#39; i&#39;的客户ID进行比较。在你的数组中。你要做的是比较&#39; y&#39;的指数的值。数组中的位置。否则,您只是检查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);