【问题标题】:Dynamic Object Destructuring动态对象解构
【发布时间】:2021-06-23 13:53:54
【问题描述】:

我正在尝试找出一种基于属性名称的动态列表/数组来解构对象的方法。

说,我有一个对象:

let individual = {
    id: 1,
    fullname: 'User Name',
    sex: 'M',
    birthdate: new Date(1975, 3, 15)
};

还有一个带有属性名的动态数组:

let properties = ['id', 'fullname','sex'];

有没有办法简单地得到一个只包含数组中指定属性的结果对象:

{
    id: 1,
    fullname: 'User Name',
    sex: 'M'
}

【问题讨论】:

  • 问的真实世界背景是什么?是过滤的应用吗?你想达到什么目的
  • lodash 'pick' 以这种方式工作,如果库的使用适合您。 lodash.com/docs/4.17.15#pick

标签: javascript destructuring


【解决方案1】:

我不确定它是否可以通过解构来完成,但可以通过几个函数来完成。

let individual = {
  id: 1,
  fullname: 'User Name',
  sex: 'M',
  birthdate: new Date(1975, 3, 15)
};
let properties = ['id', 'fullname','sex'];

let result = Object.fromEntries(properties.map(prop => [prop, individual[prop]]));

console.log(result);

【讨论】:

  • 我喜欢fromEntries的用法
【解决方案2】:

只是为了好玩。一种动态解构)

// Set dynamic destructure function
const dd = (x, y, z = {}) => { for(e of y) { ({[e]:z[e]} = x); } return z; };

// Old object
let individual = {
    id: 1,
    fullname: 'User Name',
    sex: 'M',
    birthdate: new Date(1975, 3, 15)
};

// Property names to copy
let properties = ['id', 'fullname','sex'];

// Do dynamic destructure
console.log(dd(individual, properties));

【讨论】:

    【解决方案3】:

    带有reduce的“动态”,不限于三个字段。

    properties.reduce((acc, curr )=> { acc[curr] = individual[curr];
    return acc;
     } , {})
    

    【讨论】:

      猜你喜欢
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      相关资源
      最近更新 更多