简体   繁体   中英

Get parent array key in deep nested object using lodash

I'm using Lodash JavaScript library in my project and have a problem in getting the parent array key object filtered object:

I've the following data:

var data = {
 5: [{
  id: "3",
  label: "Manish"
 }, {
  id: "6",
  label: "Rahul"
 }, {
  id: "7",
  label: "Vikash"
 }],
 8: [{
  id: "16",
  label: "Pankaj"
 }, {
  id: "45",
  label: "Akash"
 }],
 9: [{
  id: "15",
  label: "Sunil"
 }]
}

My requirement is if I've the array of [6,16] then I want a new result array containing values 5,8 because these two array keys have objects which contain id:"6" and id:"16"

I tried it using _.flatten and _.pick method but could not work. I used the following code;

var list = [];
_.each(data, function(item){
    list.push(_.omit(item, 'id'));
    list.push(_.flatten(_.pick(item, 'id')));
});
var result = _.flatten(list);
console.log(result);
var res = _([6, 16]).map(function(id){
    return _.findKey(data, function(arr){
        return _.some(arr, {id: new String(id)});
    })
}).compact().uniq().value();

If simple javascript solution is okay with you then

var searchId=[6,16];  
var newArr = []; 
for ( key in data ){
   data[key].forEach( function(innerValue){
      if ( searchId.indexOf( Number(innerValue.id) ) != -1 ) newArr.push( key );
   } ); 
}

console.log(newArr);

try this:

( hope im not missing some syntax )

var result = [];
var filterArray = [6,16];
_.each(filterArray, function(item){   
 _.merge(result,_.filter(data, function(o) { return _.contains(o,{id:item}) }));
});

Using _.pickBy this problem is solved simply:

var myArr = [6, 16]

var res = _.pickBy(data, function (value) {
    return _(value).map('id').map(_.toNumber).intersection(myArr).size();
});

console.log(res)

https://jsfiddle.net/7s4s7h3w/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM