Ajay Srikanth
Ajay Srikanth

Reputation: 1185

Compare object with an array

I've an object and the array as shown below and I wanted to remove all the properties of the object except those listed in the array. Can someone help me with a good lodash function to do this.

object : {A:1,B:2,C:3,D:4} 
array: [{type:B,value:xyz,order:1},{type:D,value:abc,order:0}]

I want the object to be {B:2,D:4} after the operation

Upvotes: 1

Views: 60

Answers (3)

Matt D. Webb
Matt D. Webb

Reputation: 3314

You can use _.pick along with _.map to achieve this:

let obj = { A:1, B:2, C:3, D:4 };
let arr = [{ type:'B', value:'xyz', order:1 },{ type:'D', value:'abc', order:0 }];

let output = _.pick(obj, _.map(arr, 'type'));

console.log(output); // { B:2, D: 4 }

Example: JsFiddle

Lodash Docs:

_.map(): link

_.pick(): link

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

Use _.pick like this:

var result = _.pick(object, array);

var object = {
  A: 1,
  B: 2,
  C: 3,
  D: 4
};

var array = ["B", "D"];

var result = _.pick(object, array);

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

EDIT:

You should first use _.map to get the keys and then use _.pick like this:

var result = _.pick(object, _.map(array, function(e) {
  return e.type;
}));

or using arrow functions like this:

var result = _.pick(object, _.map(array, e => e.type));

or even shorter using the iteratee argument like this:

var result = _.pick(object, _.map(array, "type"));

var object = {
  A: 1,
  B: 2,
  C: 3,
  D: 4
};

var array = [{type: "B", value: "xyz", order: 1}, {type: "D", value: "abc", order: 0}];

var result = _.pick(object, _.map(array, "type"));

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

Upvotes: 3

guest271314
guest271314

Reputation: 1

You can use Object.assign(), Array.prototype.map() , spread element, computed property, to assign result of filtering type properties to object

var object = {A:1,B:2,C:3,D:4} 
var array = [{type:"B",value:"xyz",order:1},{type:"D",value:"abc",order:0}];
object = Object.assign({}, ...array.map(({type}) => ({[type]:object[type]})));

console.log(object);

Upvotes: 2

Related Questions