在另一个数组内的数组内查找对象

fel*_*ner 4 javascript arrays functional-programming object

let bigArray = [
{
    Name: 'Trump',
    children: [
                 {Name: 'TrumpChild1', City: 'city1'}, 
                 {Name: 'TrumpChild2', City: 'city2'}
    ]
},
{
    Name: 'Barack Obama',
    children: [
                 {Name: 'Barack Obama Child1', City: 'city3'}, 
                 {Name: 'Barack Obama Child2', City: 'city4'}
    ]
},
{
    Name: 'Clinton',
    children: [
                 {Name: 'Clinton Child 1', City: 'city5'}, 
                 {Name: 'Clinton Child2', City: 'city6'}
    ]
},
Run Code Online (Sandbox Code Playgroud)

]

我想从另一个数组中的数组中找到一个对象

bigArray.find(b => b.children.find(c=>c.City === 'city1'))
Run Code Online (Sandbox Code Playgroud)

上面的代码返回 ARRAY 父亲

bigArray.forEach(b => b.children.find(c=>c.City === 'city1'))
Run Code Online (Sandbox Code Playgroud)

这个返回未定义

返回所需对象的最佳方法是什么?

Zoh*_*jaz 6

您可以先将此数组展平为内部对象数组,然后使用filter()find()

let bigArray = [
  {
      Name: 'Trump',
      children: [
                   {Name: 'TrumpChild1', City: 'city1'}, 
                   {Name: 'TrumpChild2', City: 'city2'}
      ]
  },
  {
      Name: 'Barack Obama',
      children: [
                   {Name: 'Barack Obama Child1', City: 'city3'}, 
                   {Name: 'Barack Obama Child2', City: 'city4'}
      ]
  },
  {
      Name: 'Clinton',
      children: [
                   {Name: 'Clinton Child 1', City: 'city5'}, 
                   {Name: 'Clinton Child2', City: 'city6'}
      ]
  }
];

let all = bigArray.reduce((prev, next) => prev.concat(next.children), []);
let result = all.find(obj => obj.City === 'city1');
console.log(result);

// if there can be multiple matches then use filter
let results = all.filter(obj => obj.City === 'city1');
console.log(results);
Run Code Online (Sandbox Code Playgroud)