lodash pick:如果没有设置密钥,则设置值

时间:2017-07-04 21:44:43

标签: javascript lodash

我有以下两个数组:

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

我想清理resultsArr,使其只有headerKeys中找到的密钥。 我想要的输出如下:

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

这是我目前正在使用的代码:

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

输出:

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

它非常接近我想要的,但它不会显示address,因为它没有设置。反正有没有强制它显示密钥,即使它没有价值?

另外,如果您对如何改善我的lodash链有建议,那就太棒了。

4 个答案:

答案 0 :(得分:4)

您可以使用_.defaults()添加缺失的密钥:

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>

答案 1 :(得分:2)

您可以创建一个函数getModel()来返回您的模型,然后不使用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)

答案 2 :(得分:1)

Ecmascript5替代方案:

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

resultsArr = resultsArr.map(function(o,i){
    var new_obj = {};
    headerKeys.forEach(function(k){
        new_obj[k] = o[k] || "";
    });
    return new_obj;
});

console.log(resultsArr);

答案 3 :(得分:0)

与原始代码类似,您可以在_.set函数中添加_.map函数:https://codepen.io/aprouja1/pen/xrzRjN?editors=0010

_.map(resultsArr,(el)=>{
  return _.pick(_.set(el,'address',""),headerKeys)
})