动态对象解构
Dynamic Object Destructuring
我正在尝试找出一种方法来根据 属性 名称的动态 list/array 解构对象。
说,我有一个对象:
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'
}
我不确定它是否可以通过解构来完成,但它可以简单地通过几个函数来完成。
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);
纯属娱乐。一种动态解构)
// 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));
"dynamic" with reduce,不限于三个字段。
properties.reduce((acc, curr )=> { acc[curr] = individual[curr];
return acc;
} , {})
我正在尝试找出一种方法来根据 属性 名称的动态 list/array 解构对象。
说,我有一个对象:
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'
}
我不确定它是否可以通过解构来完成,但它可以简单地通过几个函数来完成。
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);
纯属娱乐。一种动态解构)
// 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));
"dynamic" with reduce,不限于三个字段。
properties.reduce((acc, curr )=> { acc[curr] = individual[curr];
return acc;
} , {})