用Lodash删除对象属性 [英] Removing object properties with Lodash
问题描述
我必须删除与我的模型不匹配的不需要的对象属性.如何用Lodash实现它?
I have to remove unwanted object properties that do not match my model. How can I achieve it with Lodash?
我的模特是:
var model = {
fname: null,
lname: null
}
在发送到服务器之前,我的控制器输出为:
My controller output before sending to the server will be:
var credentials = {
fname: "xyz",
lname: "abc",
age: 23
}
如果我使用
_.extend(model, credentials)
我也获得了年龄财产.我知道我可以使用
I am getting the age property too. I am aware I can use
delete credentials.age
但是,如果我有10个以上不需要的对象,该怎么办?我可以用Lodash实现吗?
but what if I have more than 10 unwanted objects? Can I achieve it with Lodash?
推荐答案
使用 _.keys()
,然后使用 _.pick()
将属性从凭据
提取到新对象:
Get a list of properties from model
using _.keys()
, and use _.pick()
to extract the properties from credentials
to a new object:
var model = {
fname:null,
lname:null
};
var credentials = {
fname:"xyz",
lname:"abc",
age:23
};
var result = _.pick(credentials, _.keys(model));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
如果您不想使用Lodash,则可以使用 Array.prototype.reduce()
:
If you don't want to use Lodash, you can use Object.keys()
, and Array.prototype.reduce()
:
var model = {
fname:null,
lname:null
};
var credentials = {
fname:"xyz",
lname:"abc",
age:23
};
var result = Object.keys(model).reduce(function(obj, key) {
obj[key] = credentials[key];
return obj;
}, {});
console.log(result);
这篇关于用Lodash删除对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!