使用 lodash 重置对象数组
reset array of objects with lodash
如何重置数组中与 'db' 不同的对象的属性?
我需要将 'db' 以外的其他设置为空字符串。
var arr = [
{
"db": "RHID",
"prv_value": "1",
"nxt_value": "1",
"diagnostic": "1"
},
{
"db": "CD_DOC_ID",
"prv_value": "2",
"nxt_value": "2",
"diagnostic": "2"
},
...
]
使用map函数,它接受一个数组和一个转换函数。它将每个元素传递给函数进行修改。
_.map(arr, function(curr) {
for (var prop in curr) {
// Please read http://phrogz.net/death-to-hasownproperty
if (curr.hasOwnProperty(prop) && prop != 'db') {
curr[prop] = '';
}
}
return curr;
});
我会这样做:
_.map(arr, function(i) {
return _.assign(
_(i).omit('db').mapValues(_.constant('')).value(),
_.pick(i, 'db')
);
});
本质上,这使用 map() to create an array of new objects. It's using assign() to build the mapped object (it's basically concatenating two objects). The first argument passed to assign()
is the object with the db
property removed. This is done using omit(). With this property removed, we can use mapValues() 将所有内容设置回空字符串。
现在我们所要做的就是将 db
属性 添加回去,这就是我们使用 assign()
的原因。 pick() 函数用于获取 db
值。
如何重置数组中与 'db' 不同的对象的属性? 我需要将 'db' 以外的其他设置为空字符串。
var arr = [
{
"db": "RHID",
"prv_value": "1",
"nxt_value": "1",
"diagnostic": "1"
},
{
"db": "CD_DOC_ID",
"prv_value": "2",
"nxt_value": "2",
"diagnostic": "2"
},
...
]
使用map函数,它接受一个数组和一个转换函数。它将每个元素传递给函数进行修改。
_.map(arr, function(curr) {
for (var prop in curr) {
// Please read http://phrogz.net/death-to-hasownproperty
if (curr.hasOwnProperty(prop) && prop != 'db') {
curr[prop] = '';
}
}
return curr;
});
我会这样做:
_.map(arr, function(i) {
return _.assign(
_(i).omit('db').mapValues(_.constant('')).value(),
_.pick(i, 'db')
);
});
本质上,这使用 map() to create an array of new objects. It's using assign() to build the mapped object (it's basically concatenating two objects). The first argument passed to assign()
is the object with the db
property removed. This is done using omit(). With this property removed, we can use mapValues() 将所有内容设置回空字符串。
现在我们所要做的就是将 db
属性 添加回去,这就是我们使用 assign()
的原因。 pick() 函数用于获取 db
值。