在不使用嵌套循环的情况下在对象内执行深度搜索(lodash)

时间:2017-08-21 00:01:00

标签: javascript lodash

我正在尝试检查是否在包含在对象深处的数组中找到了值,而不必使用多个for& for in循环。我想知道是否有一种优雅的方式来实现这一目标。我的第一个想法是使用lodash的_.includes,但它似乎没有迭代我的子对象中的数组。

//collection (i'm trying to reach person_id in the people array)
var tables = {
 12: {
  table_info: {
   name: 'Test'
  },
  people: [ //I want to check inside of this array
   {
    person_id: 123
   },
   {
    person_id: 233
   }
  ]
 }

//what i'm looping over to match up id's
var people = [
 {
  name: 'John Doe',
  id: 123
 },
 {
  name: 'Jane Doe',
  id: 245
 }
]

//loop
for (var i = 0; i < people.length; i++) 
{
  if (_.includes(tables, people[i].id)) //would love a simple solution like this
  {
    console.log("match");
  }
  else
  {
    console.log("no match");
  }
}

1 个答案:

答案 0 :(得分:0)

为什么不创建自己的函数并在知道数据结构时使用它?

&#13;
&#13;
//collection
var tables = {
 12: {
    table_info: {
      name: 'Test'
    },
    people: [
     {
      person_id: 123
     },
     {
      person_id: 233
     }
    ]
  }
};

var peopleToFind = [
 {
  name: 'John Doe',
  id: 123
 },
 {
  name: 'Jane Doe',
  id: 245
 }
];

function findPeopleInTables(people, tables){
  let peopleFound = [];
  for (var key in tables) {
    // to make sure it doesnt come from prototype
    if (tables.hasOwnProperty(key)) {
      tables[key].people.forEach(function (person){
          peopleToFind.forEach(function(personToFind){
            if (person.person_id === personToFind.id){
              peopleFound.push(personToFind);
            }
          });
        });
    }
  }
  return peopleFound;
}

let foundPeople = findPeopleInTables(peopleToFind, tables);
foundPeople.forEach(function(person){
  console.log('found "' + person.name + '" with id ' + person.id);
});
&#13;
&#13;
&#13;

您也可以使用递归方法搜索对象:

&#13;
&#13;
function findValueInObject(value , object){
    let type = typeof(object);
    if(type !== 'string'  && type !== 'number'  && type !== 'boolean'){
        for (var key in object) {
            // to make sure it doesnt come from prototype
            if (object.hasOwnProperty(key)) {
                if( findValueInObject(value , object[key])){
                    return true;
                }
            }
        }
    }
    if(object === value){
        return true;
    }
    return false;
}


//collection
var tables = {
 12: {
    table_info: {
      name: 'Test'
    },
    people: [
     {
      person_id: 123
     },
     {
      person_id: 233
     }
    ]
  }
};

var peopleToFind = [
 {
  name: 'John Doe',
  id: 123
 },
 {
  name: 'Jane Doe',
  id: 245
 }
];

peopleToFind.forEach(function(person){
    if(findValueInObject(person.id, tables)){
        console.log('matched: ' + person.id + ' '+ person.name);
    }
});
&#13;
&#13;
&#13;