假设我有一个对象:
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' }
我怎样才能做到呢?
当前回答
如果你正在使用ES6,有一种非常简洁的方法来使用解构来做到这一点。析构允许您轻松地使用扩展添加到对象,但它也允许您以相同的方式创建子集对象。
const object = {
a: 'a',
b: 'b',
c: 'c',
d: 'd',
}
// Remove "c" and "d" fields from original object:
const {c, d, ...partialObject} = object;
const subset = {c, d};
console.log(partialObject) // => { a: 'a', b: 'b'}
console.log(subset) // => { c: 'c', d: 'd'};
其他回答
还有一个解决方案:
var subset = {
color: elmo.color,
height: elmo.height
}
到目前为止,这看起来比任何答案都更具可读性,但也许这只是我的想法!
两种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);
就像这个线程上的几个人一样,我同意evert的观点,最明显的老派方法实际上是最好的,但是为了好玩,让我提供另一种不可取的方法来做它在某些情况下,比如当你已经定义了你的子集,你想从另一个对象复制属性到它,其中包含一个超集或交叉集的属性。
设set = {a: 1, b: 2, c: 3}; 让子集= {a: null, b: null}; 尝试{ Object.assign (Object.seal(子集),集); } catch (e) { console.log('我想这样做<(^.^)^'); } console.log(子集);
补充另一种深奥的方法,这也很有效:
var obj = {a: 1, b:2, c:3}
var newobj = {a,c}=obj && {a,c}
// {a: 1, c:3}
但是你必须把道具名写两遍。
function splice()
{
var ret = new Object();
for(i = 1; i < arguments.length; i++)
ret[arguments[i]] = arguments[0][arguments[i]];
return ret;
}
var answer = splice(elmo, "color", "height");