简体   繁体   English

在对象内执行深度搜索而无需使用嵌套循环(lodash)

[英]Performing deep search within object without using nested loops (lodash)

I am trying to check if a value is found inside of an array contained deep in an object without having to use multiple for & for in loops. 我试图检查是否在对象深处包含的数组中找到一个值,而不必使用for和for循环中的多个。 I want to know if there is an elegant way to achieve this. 我想知道是否有一种优雅的方法来实现这一目标。 My first thought was to use lodash's _.includes, but it doesn't seem to iterate over the array in my sub-object. 我的第一个想法是使用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");
  }
}

why not create your own function and use it if you know the data structure? 如果不了解数据结构,为什么不创建自己的函数并使用它呢?

 //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); }); 

also you can search in objects using recursive methods : 您也可以使用递归方法搜索对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM