如何从对象数组中的嵌套数组中访问特定值? [英] How to access specific value from a nested array within an object array?

查看:279
本文介绍了如何从对象数组中的嵌套数组中访问特定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从对象数组中的嵌套数组中获取特定的字段值。我假设我使用map,但每次我以这种方式使用它时,我会在两个空对象中嵌套两个空数组。我知道这是错的,我只是在显示我的思考过程。

I am trying to get a specific field value from a nested array within an object array. I'm assuming I'd use map, but every time I use it in this way I get two empty arrays nested inside two empty objects. I know this is wrong, I'm just showing where my thinking process is going.

function getChildArray(item, index) {
   var x = [item.hobbies]
      return x
}

console.log(parentArray.map(getChildArray))

这是我的文档结构示例:

This is an example of my document structure:

[  
   {  
      "id":12345678900,
      "name":"Jasmin",
      "age":27,
      "hobbies":[  
         {  
            "id":1221,
            "name":"hiking",
            "when":"anytime"
         },
         {  
            "id":9865,
            "name":"eating",
            "when":"all the time"
         }
      ]
   },
   {  
      "id":223456789001,
      "name":"Joe",
      "age":35,
      "hobbies":[  
         {  
            "id":989,
            "name":"gaming",
            "when":"anytime"
         },
         {  
            "id":2355,
            "name":"online gaming",
            "when":"all the time"
         }
      ]
   }
]

我怎么样,因为例如,能够仅按名称检索Joe的爱好列表吗?

推荐答案

var joe = parentArray.find(function (item) {
    return item.name === 'Joe';
});

if (joe) {
    var joesHobbiesNames = joe.hobbies.map(function (hobbie) {
       return hobbie.name;
    });
}

或在ES6中

var joe = parentArray.find((item) => item.name === 'Joe');

if (joe) {
    var joesHobbiesNames = joe.hobbies.map((hobbie) => hobbie.name);
}

这篇关于如何从对象数组中的嵌套数组中访问特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆