假设我有一个对象:
elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
我想用它的属性子集创建一个新对象。
// pseudo code
subset = elmo.slice('color', 'height')
//=> { color: 'red', height: 'unknown' }
我怎样才能做到呢?
假设我有一个对象:
elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
我想用它的属性子集创建一个新对象。
// pseudo code
subset = elmo.slice('color', 'height')
//=> { color: 'red', height: 'unknown' }
我怎样才能做到呢?
当前回答
动态属性的解构赋值
这个解决方案不仅适用于你的具体例子,而且更普遍适用:
const subset2 = (x, y) = > ({[x]: [y]: b}) = > ({[x]: [y]: b}); const subset3 = (x, y, z) = > ({[x]: [y]: b [z]: c}) = > ({[x]: [y]: b [z]: c}); // const subset4… Const o = {a:1, b:2, c:3, d:4, e:5}; const pickBD = subset2("b", "d"); const pickACE = subset3("a", "c", "e"); console.log ( pickBD(o), // {b:2, d:4} pickACE(o) // {a:1, c:3, e:5} );
您可以轻松地定义subset4等,以考虑更多的属性。
其他回答
两种Array.prototype.reduce:
const selectable = {a: null, b: null};
const v = {a: true, b: 'yes', c: 4};
const r = Object.keys(selectable).reduce((a, b) => {
return (a[b] = v[b]), a;
}, {});
console.log(r);
这个答案使用了神奇的逗号运算符: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
如果你想要更花哨,这个更紧凑:
const r = Object.keys(selectable).reduce((a, b) => (a[b] = v[b], a), {});
把所有这些放到一个可重用的函数中:
const getSelectable = function (selectable, original) {
return Object.keys(selectable).reduce((a, b) => (a[b] = original[b], a), {})
};
const r = getSelectable(selectable, v);
console.log(r);
我建议看看Lodash;它有很多实用函数。
例如,pick()就是你要找的东西:
var subset = _.pick(elmo, ['color', 'height']);
小提琴
在这个问题中,解构为动态命名的变量在JavaScript中是不可能的。
要动态设置键,可以使用reduce函数而不改变对象,如下所示:
const get子集= (obj,…keys) =>个key。Reduce ((a, c) =>({…A, [c]: obj[c]}), {}); Const elmo = { 颜色:红色, 讨厌:没错, 高度:“未知”, Meta: {1: '1', 2: '2'} } const子集= get子集(elmo, 'color', '烦人') console.log(子集)
应该注意的是,你是在每次迭代中创建一个新对象,而不是更新一个克隆。——mpen
下面是一个使用reduce和单个克隆的版本(更新传入的初始值以reduce)。
const get子集= (obj,…keys) =>个key。Reduce ((acc, curr) => { Acc [curr] = obj[curr] 返回acc }, {}) Const elmo = { 颜色:红色, 讨厌:没错, 高度:“未知”, Meta: {1: '1', 2: '2'} } const子集= get子集(elmo, '烦人','height', 'meta') console.log(子集)
补充另一种深奥的方法,这也很有效:
var obj = {a: 1, b:2, c:3}
var newobj = {a,c}=obj && {a,c}
// {a: 1, c:3}
但是你必须把道具名写两遍。
使用对象解构和属性简写
Const对象= {a: 5, b: 6, c: 7}; const = (({a、c }) => ({ a、c}))(对象); console.log(选择);// {a: 5, c: 7}
来自Philipp Kewisch:
这实际上只是一个被即时调用的匿名函数。所有这些都可以在MDN上的解构分配页面上找到。这是一个展开的形式
Let unwrap = ({a, c}) => ({a, c}); 让unwrap2 = function({a, c}){返回{a, c};}; Let selected = unwrap({a: 5, b: 6, c: 7}); 让picke2 = unwrap2({a: 5, b: 6, c: 7}) console.log(选) console.log (picked2)