如何从对象数组中的嵌套数组中访问特定值?

时间:2016-07-03 04:02:40

标签: javascript json multidimensional-array

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

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

console.log(parentArray.map(getChildArray))

这是我的文档结构的一个例子:

[  
   {  
      "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的爱好列表?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

由于array.find尚未在所有浏览器中提供,并且您可能没有使用构建工具,因此这是一种完整的ES5方式。它使用filtermap



var data = [{ 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' }]}];


function getHobbiesByName(name) {
  return data.filter(function(person) {
    return (person.name == name);
  })[0].hobbies.map(function(hobby) {
    return hobby.name
  })
}

console.log(getHobbiesByName('Joe'))




答案 2 :(得分:0)

一个快速函数,用于返回具有该属性的所需属性和值的项目:

data = [{id:1,name:'Bob',hobbies:['a','b']},{id:2,name:'Alice',hobbies:['c','d']}];

function getPerson(property,value){
 for(var i=0;i<data.length;i++) if(data[i][property] == value) return data[i];
 return {};
}

测试:

console.log(getPerson('name','Bob'));
console.log(getPerson('name','Bob').hobbies);