underscore.js:_.pick提取数组中对象内的属性

时间:2016-10-05 18:49:13

标签: javascript underscore.js

以下是我拥有的对象:

{
  "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"
    }
  ]
}

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

{
  "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部分内容?

2 个答案:

答案 0 :(得分:3)

而不是选择多个级别,我只是做

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}) =>语法从参数列表中直接从该对象中提取所需的属性。然后,对于函数的返回值,我们使用object literal简写指定一个仅包含这些属性的新对象,这允许我们只写{p1, p2}以获得等效的{p1: p1, p2: p2}。因此,选择属性p1p1的最简单情况是

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

在上面的示例中,我们在顶层使用此模式一次,然后再次通过Detailsmap数组的每个元素中选择。

当然,如果您真的想要,或者认为上述内容过于混乱,您可以随时选择“手动”:

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', ...);
});

答案 1 :(得分:-1)

可能这可以工作

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