Итерация по данным связанного массива для сопоставленного элемента, используя Lodash - PullRequest
0 голосов
/ 17 октября 2018

Есть ли в lodash способ найти подходящее имя (предполагается уникальное) и выполнить итерацию по массиву связанных местоположений, т.е. сначала вернуть бит массива соответствующего элемента (filter? PickBy? И т. Д.) И выполнить итерацию по нему.

var locations = [ {name:"dave", location:["home","work","pub"]},
                  {name:"alice", location:["school","college","university"]},
                  {name:"fred", location:["us","uk"]} ];

Поиск "fred", должен вернуть:

0:us
1:uk

Я могу сделать это с _.filter и вложенным _.forEach, но надеялся на что-то лучшее, чем это:

// _.filter returns the entire element that matches name=who
_.forEach(_.filter( locations, { name:who } ), function(pv,pk){ 
    // returns the array of locations for "who" in 'pv'
    _.forEach(pv.location, function(value,key) { 
        // iterate through the location array one at a time
        console.log ( key+":"+value );
    })
});

Ответы [ 2 ]

0 голосов
/ 18 октября 2018
// _.filter returns the entire element that matches name=who
_.forEach(_.find( locations, { name:"fred" } ).location, function(value,key){ 
    // iterate through the location array one at a time
    console.log ( key+":"+value );
});
0 голосов
/ 18 октября 2018

Не совсем понятно, что вам нужно, поэтому следуют два варианта, ни один из которых не требует lodash:

const locations = [{name:"dave", location:["home","work","pub"]},
                  {name:"alice", location:["school","college","university"]},
                  {name:"fred", location:["us","uk"]} ];


// Will work even if you have multiple Freds in your data you could also 
// use filter + map here, but reduce does it one shot
//
const allMatches = (name) => {
    return locations.reduce(((memo, entry, index) => {
      if(entry.name === name) {
          memo[name] = entry.location;
      }
      return memo;
    }), {})
};

// If you know you will only have a single "Fred", then it becomes even simpler
//
const singleMatch = (name) => {
    return locations.find(entry => entry.name === name).location;
};


console.log(singleMatch('fred'));
console.log(allMatches('fred'));
...