1

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
Ajay Srikanth
  • 1,095
  • 4
  • 22
  • 43

3 Answers3

3

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>
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
2

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);
guest271314
  • 1
  • 15
  • 104
  • 177
  • what is the ... in Object.assign() ? Could you please explain that syntax. I've just started as full time js developer. I'm having trouble understanding few syntax here and there. – Ajay Srikanth Mar 13 '17 at 21:50
  • @AjaySrikanth See [What is SpreadElement in ECMAScript documentation? Is it the same as Spread operator at MDN?](http://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper) – guest271314 Mar 13 '17 at 21:52
0

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

Matt D. Webb
  • 3,216
  • 4
  • 29
  • 51