使用lodash删除对象属性

Ala*_*ene 51 lodash

我必须删除与我的模型不匹配的不需要的对象属性.我怎么能用lodash实现它.

我的模型是

var model = {
   fname:null,
   lname:null
}
Run Code Online (Sandbox Code Playgroud)

在发送到服务器之前我的控制器输出将是

var credentials = {
    fname:"xyz",
    lname:"abc",
    age:23
}
Run Code Online (Sandbox Code Playgroud)

如果我使用

 _.extend (model, credentials)
Run Code Online (Sandbox Code Playgroud)

我也正在获得年龄的财产.我知道我可以使用

delete credentials.age
Run Code Online (Sandbox Code Playgroud)

但如果我有超过10个不需要的对象怎么办?我可以用lodash实现它吗?

Chr*_*ris 119

您可以从白名单或黑名单方式接近它:

// Black list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);

// White list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);
Run Code Online (Sandbox Code Playgroud)

如果它是可重用的业务逻辑,您也可以将其分解:

// Partial out a black list version
var clean = _.partial(_.omit, _, ['age']); 

// and later
var result = clean(credentials);
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案,因为要删除的函数是`_.omit`,而`_.pick`指定了您想要的那个(相反) (4认同)
  • 黑名单是这个问题的预期答案.应该是正确的答案 (3认同)
  • **警告:** - [省略将在第 5 版中删除](https://github.com/lodash/lodash/wiki/Roadmap)(请参阅 [此处的讨论](https://github.com /lodash/lodash/issues/2930)) (2认同)

Ori*_*ori 49

model使用中获取属性列表_.keys(),并使用从新_.pick()属性中提取属性credentials:

var model = {
   fname:null,
   lname:null
};

var credentials = {
    fname:"xyz",
    lname:"abc",
    age:23
};

var result = _.pick(credentials, _.keys(model));

console.log(result);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

如果您不想使用lodash,可以使用Object.keys(),并且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);
Run Code Online (Sandbox Code Playgroud)


小智 8

Lodashunset适合删除一些不需要的密钥。

const myObj = {
    keyOne: "hello",
    keyTwo: "world"
}

unset(myObj, "keyTwo");

console.log(myObj); /// myObj = { keyOne: "hello" }
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以使用 _.pick 轻松完成此操作:

var model = {
  fname: null,
  lname: null
};

var credentials = {
  fname: 'abc',
  lname: 'xyz',
  age: 2
};

var result = _.pick(credentials, _.keys(model));


console.log('result =', result);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

但是您可以简单地使用纯 JavaScript(特别是如果您使用ECMAScript 6),如下所示:

const model = {
  fname: null,
  lname: null
};

const credentials = {
  fname: 'abc',
  lname: 'xyz',
  age: 2
};

const newModel = {};

Object.keys(model).forEach(key => newModel[key] = credentials[key]);

console.log('newModel =', newModel);
Run Code Online (Sandbox Code Playgroud)