Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash pick: set value if key not set

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.

like image 919
kei Avatar asked Oct 23 '25 00:10

kei


2 Answers

You can use _.defaults() to add the missing keys:

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

/** create once the defaults object from the headerKeys **/
var defaultsObj = _(headerKeys)
  .mapKeys()
  .mapValues(function() { return ""; })
  .value();

var result = resultsArr.map(function(obj) {
  return _(obj)
    .pick(headerKeys)
    .defaults(defaultsObj) // apply the defaults
    .value();
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 178
Ori Drori Avatar answered Oct 25 '25 16:10

Ori Drori


You can create a function getModel() to return your model, and then without lodash:

getModel= ()=>({ title:'', name:'', address:'default' });

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

var result = resultsArr.map(function(obj) {
  var model = getModel();
  for (var key in model) {
    if (obj.hasOwnProperty(key)) {
      model[key] = obj[key];
    }
  }
  return model;
});

console.log(result)
like image 21
Washington Guedes Avatar answered Oct 25 '25 15:10

Washington Guedes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!