Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am trying to filter objects from two array of objects on the basis of name along with few conditions using lodash. Here are the arrays

var param1 = [{'name': 'sa', 'value':'sample'},
              {'name': 'sam', 'value':''}];

var param2 = [{'name': 's1', 'value':'ex1'},
           {'name': 's2', 'value':'ex2'},
           {'name': 's3', 'value':'ex3'},
           {'name': 'sa', 'value':'ex4'}];

I wanted to check the objects of param1[by name] existence in param2, if so return the param1 object along with the rest of the objects left within param2. So the final result has to be some thing like this:

result= [{'name': 's1', 'value':'ex1'},
         {'name': 's2', 'value':'ex2'},
         {'name': 's3', 'value':'ex3'},
         {'name': 'sa', 'value':'sample'}];

I have tried with couple of lodash functions such as _.filter, _.map, _.difference but am clueless on how to chain this functionality and get the appropriate result.

share|improve this question

Dont think you will need lodash for it, You can use array forEach to execute it

var param1 = [{
  'name': 'sa',
  'value': 'sample'
}, {
  'name': 'sam',
  'value': ''
}];

var param2 = [{
  'name': 's1',
  'value': 'ex1'
}, {
  'name': 's2',
  'value': 'ex2'
}, {
  'name': 's3',
  'value': 'ex3'
}, {
  'name': 'sa',
  'value': 'ex4'
}];

param1.forEach(function(item) {
     param2.forEach(function(item2){
      if(item.name ==item2.name){
       item2.value = item.value
     }
   })

})

console.log(param2)

DEMO

share|improve this answer

Lodash with _.forEach and _.find.

var param1 = [{'name': 'sa', 'value':'sample'}, {'name': 'sam', 'value':''}];
var param2 = [{'name': 's1', 'value':'ex1'}, {'name': 's2', 'value':'ex2'}, {'name': 's3', 'value':'ex3'}, {'name': 'sa', 'value':'ex4'}];

_.forEach(param1, a => {
    var o = _.find(param2, b => a.name === b.name);
    if (o) {
        o.value = a.value;
    }
});

console.log(param2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Plain ES6 Javascript

var param1 = [{'name': 'sa', 'value':'sample'}, {'name': 'sam', 'value':''}];
var param2 = [{'name': 's1', 'value':'ex1'}, {'name': 's2', 'value':'ex2'}, {'name': 's3', 'value':'ex3'}, {'name': 'sa', 'value':'ex4'}];

param1.forEach(a => {
    var o = param2.find(b => a.name === b.name);
    if (o) {
        o.value = a.value;
    }
});

console.log(param2);

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.