How to access specific value from a nested array within an object array?

后端 未结 3 1220
抹茶落季
抹茶落季 2021-01-27 17:35

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 nest

相关标签:
3条回答
  • 2021-01-27 18:00

    Since array.find is not available in all browsers yet, and you may not be using a build tool, here is a complete ES5 way. It uses filter and map:

    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'))

    0 讨论(0)
  • 2021-01-27 18:13

    A quick function to return an item with the desired property and value of that property :

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

    And a test :

    console.log(getPerson('name','Bob'));
    console.log(getPerson('name','Bob').hobbies);
    
    0 讨论(0)
  • 2021-01-27 18:20
    var joe = parentArray.find(function (item) {
        return item.name === 'Joe';
    });
    
    if (joe) {
        var joesHobbiesNames = joe.hobbies.map(function (hobbie) {
           return hobbie.name;
        });
    }
    

    Or in ES6

    var joe = parentArray.find((item) => item.name === 'Joe');
    
    if (joe) {
        var joesHobbiesNames = joe.hobbies.map((hobbie) => hobbie.name);
    }
    
    0 讨论(0)
提交回复
热议问题