使用Lodash遍历关联数组数据以匹配元素

时间:2018-10-17 09:56:27

标签: lodash

在lodash中是否有一种方法可以找到匹配的名称(假设是唯一的)并在关联位置的数组上进行迭代,即最初返回匹配元素的数组位(filter?pickBy?等)并在其上进行迭代。 / p>

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 :(得分:0)

尚不清楚您需要什么,因此有两个选择,都不需要lodash:

button.setImage(nil, for: .normal)

答案 1 :(得分:0)

// _.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 );
});
相关问题