简体   繁体   English

Javascript - 从一个数组中获取 object,其数组与另一个数组匹配

[英]Javascript - get object from an array, whose array matches another array

I have an array of objects ( zoo ) inside of which are some objects, and the objects have an array of objects ( animals ) in them.我有一个对象数组( zoo ),其中有一些对象,并且这些对象中有一个对象数组( animals )。 I need to filter the array, and get the objects with the same animal names, as another dynamic array in my code.我需要过滤数组,并获取具有相同动物名称的对象,作为我代码中的另一个动态数组。

zoo

  0:[...]
  1:[...]
  2:
    name:"whatevername"
    city:"whatevercity"
    animals:Array(2)
        0:
          name:"somename"
          species:"somespecies"
        1: ...
    etc:"whasover"

So if my dynamic array contains somename in it, I should get the object with index 2. How do I go about something like that?因此,如果我的动态数组中包含somename ,我应该得到索引为 2 的 object。我该如何做 go 呢?

This is the function you need:这是您需要的 function:

const search = keyword => zoos.find(({ animals }) => animals.some(({ name }) => name == keyword));

Here's a live example:这是一个活生生的例子:

 const zoos = [ { name: 'Antarctic Zoo', city: 'Chilean Villa Las Estrellas', animals: [{ name: 'Chinstrap penguin', species: 'Pygoscelis antarctica' }], }, { name: 'African Zoo', city: 'Cairo', animals: [{ name: 'Lion', species: 'Panthera leo' }], } ]; const search = keyword => zoos.find(({ animals }) => animals.some(({ name }) => name == keyword)); const result = search('Lion'); console.log(result); // { name: 'African Zoo', city: 'Cairo', animals: [ { name: 'Lion', species: 'Panthera leo' } ] }

暂无
暂无

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

相关问题 从数组中检索对象,其中另一个对象与另一个数组匹配 - retrieve object from array WHERE another object matches another array 如何从一个 object 数组获取数据到另一个 object 数组? Javascript - How to get data from an object array to another object array ? Javascript JavaScript 从一个对象数组中获取不在另一个数组中的元素 - JavaScript get elements from an object array that are not in another LoDash从子数组中找到其属性与对象数组中的值匹配的对象 - LoDash find the object whose property matches the value from array of objects with children array Javascript正则表达式将匹配项作为数组获取 - Javascript regex get matches as array 如果 object 和数组值在 javascript 中匹配,如何获取 object 密钥 - how to get the object key if the object and array value matches in javascript TS/JS - 如果数组中对象的属性与单独对象中的另一个属性匹配,则从对象数组中获取“值” - TS/JS - Get "value" from an Array of Objects if a Property of an Object from the Array matches another Property from a separate Object 从对象获取javascript数组 - get javascript array from object 在javascript中,如何获取存储在对象属性中的数组中的值,其父对象存储在数组中? - In javascript, how to get value stored in an array stored in an object property, whose parent object is stored in an array? 将数组的 object 的数组与 javascript 中的另一个数组进行比较 - compare array of object of array with an another array in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM