[英]Performing deep search within object without using nested loops (lodash)
我試圖檢查是否在對象深處包含的數組中找到一個值,而不必使用for和for循環中的多個。 我想知道是否有一種優雅的方法來實現這一目標。 我的第一個想法是使用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");
}
}
如果不了解數據結構,為什么不創建自己的函數並使用它呢?
//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); });
您也可以使用遞歸方法搜索對象:
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.