lodash pick: set value if key not set

Viewed 5905

I have the following two arrays:

var headerKeys = ["title","name","address"]
var resultsArr = [
    { title:"test 1", name: "test1", unrelatedKey: "blah" },
    { title:"test 2", name: "test2" }
]

I'd like to clean up resultsArr such that it only has the keys found in headerKeys. My desired output looks like this:

[
    { title:"test 1", name: "test1", address: "" },
    { title:"test 2", name: "test2", address: "" }
]

This is the code I'm currently using:

_.chain(resultsArr).map(function(item){
    return _.chain(item).pick(headerKeys).value()
}).value()

This outputs:

[
    { title:"test 1", name: "test1" },
    { title:"test 2", name: "test2" }
]

It's pretty close to what I want, but it will not show address since it isn't set. Is there anyway to force it to show the key even if it has no value?

Also, if you have suggestions on how to improve my lodash chain, that would be great.

4 Answers
Related