underscore.js: _.选择此选项可提取位于数组中的对象中的属性

underscore.js: _.pick to extract properties inside an object that's in an array

本文关键字:数组 属性 于数组 对象 js 选择 提取 选项 underscore      更新时间:2023-09-26

下面是我的对象:

{
  "email": "joe@example.com",
  "id": null,
  "firstName": null,
  "lastName": null,
  "createdAt": "2016-10-05T18:16:07.000Z",
  "updatedAt": "2016-10-05T18:16:07.000Z",
  "Details": [
    {
      "id": 1,
      "token": null,
      "deviceId": null,
      "code": 12345678,
      "verified": null,
      "createdAt": "2016-10-05T18:16:07.000Z",
      "updatedAt": "2016-10-05T18:16:07.000Z",
      "UserEmail": "joe@example.com"
    }
  ]
}

我希望从underscore.js库中使用pick方法并返回以下对象:

{
  "email": "joe@example.com",
  "firstName": null,
  "lastName": null,
  "Details": [
    {
      "token": null,
      "deviceId": null,
      "code": 12345678,
      "verified": null,
    }
  ]
}

我试过使用:

var modifiedObj = _.pick(obj, 'email', 'firstName', 'lastName');

返回:

{
  "email": "joe@example.com",
  "firstName": null,
  "lastName": null
}

我如何提取Details对象和其中的一些properties ?

与其选择多个层次,不如直接选择

var obj = {
  "email": "joe@example.com",
  "id": null,
  "firstName": null,
  "lastName": null,
  "createdAt": "2016-10-05T18:16:07.000Z",
  "updatedAt": "2016-10-05T18:16:07.000Z",
  "Details": [
    {
      "id": 1,
      "token": null,
      "deviceId": null,
      "code": 12345678,
      "verified": null,
      "createdAt": "2016-10-05T18:16:07.000Z",
      "updatedAt": "2016-10-05T18:16:07.000Z",
      "UserEmail": "joe@example.com"
    }
  ]
};
var newObj = (({email, firstName, lastName, Details}) =>
  ({
    email, 
    firstName, 
    lastName,
    Details: Details.map(
     ({token, deviceId, code, verified}) => ({token, deviceId, code, verified}))
  })
)(obj);
console.log(newObj);

在这种模式中,我们通过编写一个函数来"选择"ES6参数解构,我们向其传递一个对象,并使用({p1, p2}) =>语法从参数列表中提取我们想要的属性。然后,对于函数的返回值,我们指定一个只包含这些属性的新对象,使用对象文字速记,这允许我们只写{p1, p2}以获得{p1: p1, p2: p2}的等量物。选择属性p1p1最简单的例子是

(({p1, p2}) => ({p2, p2}))(obj)

在上面的例子中,我们在顶层使用了一次这种模式,然后再次通过mapDetails数组的每个元素中选择。

当然,如果你真的想这样做,或者认为上面的内容太令人困惑,你可以选择"手动":

var newObj = {
  email: obj.email,
  ...,
  Details: obj.Details.map(function(detail) {
    return {token: detail.token, ...};
  })
};

使用_.pick

如果你仍然想使用_.pick,那么你需要做两次:

var newObj = _.pick(obj, 'email', 'firstName', 'lastName', 'Details');
obj.Details = _.map(obj.Details, function(detail) {
  return detail.pick('token', ...);
});

也许这行得通

var modifiedObj = _.pick(obj, 'email', 'firstName', 'lastName','Details[0].token','Details[0].deviceId','Details[0].code','Details[0].verified');