2

I am relatively new to Lodash and I'm trying to do something that I'm sure is really easy.

I'm wondering which existing Lodash method to use to take an array of keys and an object, then return a new object containing only the properties (from the original object) that match the keys that were passed in.

let _ = require("lodash");

// DOES THE FUNCTION BELOW ALREADY EXIST?
let only = function (wanted, srcList) {
  return _.reduce(wanted, function(out,key){
    if(_.has(srcList, key)){
      out[key] = srcList[key]
    }
    return out;
  },{})
}


let src = {
  w: "This is doble vuu",
  x: "This is X",
  y: "This is why?",
  z: "This is zeee!"
};

var want = ['x','z'];

let newObject  = only(want,src);

console.log(newObject)

The code I have works, but I don't want to re-invent the proverbial wheel, no matter how simple it is.

1
  • 2
    The function you want is pick Commented Nov 16, 2017 at 18:41

2 Answers 2

2

_.pick works perfectly as suggested by Gruff Bunny in the comments. I don't know why it didn't seem more obvious when I was going through dozens of methods available in Lodash

Sign up to request clarification or add additional context in comments.

Comments

0

I believe that you want _.map.

It will return an object with the specified keys if you pass an array of strings as the second argument.

2 Comments

_.map returns an array, not an object.
true, I got confused with pick

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.