0

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);
1
  • Can jquery solution be accepted? Commented Feb 26, 2016 at 10:24

4 Answers 4

1
var res = _([6, 16]).map(function(id){
    return _.findKey(data, function(arr){
        return _.some(arr, {id: new String(id)});
    })
}).compact().uniq().value();
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

Its fine but does lodash not provide any short solution for it?
@ManishJangirBlogaddition.com sorry, I have not worked on lodash. If no one else provide you with a lodash solution (since you posted more than 15 min ago) then you can use mine.
Hi, why it is not working if searchId = $('#multiselect-dropdown').val();
not sure, what is the output of $('#multiselect-dropdown').val();
0

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

1 Comment

TypeError: _.contains is not a function
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.