假设我有一个对象:
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' }
我怎样才能做到呢?
当前回答
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");
其他回答
就像这个线程上的几个人一样,我同意evert的观点,最明显的老派方法实际上是最好的,但是为了好玩,让我提供另一种不可取的方法来做它在某些情况下,比如当你已经定义了你的子集,你想从另一个对象复制属性到它,其中包含一个超集或交叉集的属性。
设set = {a: 1, b: 2, c: 3}; 让子集= {a: null, b: null}; 尝试{ Object.assign (Object.seal(子集),集); } catch (e) { console.log('我想这样做<(^.^)^'); } console.log(子集);
对象数组
const aListOfObjects = [{
prop1: 50,
prop2: "Nothing",
prop3: "hello",
prop4: "What's up",
},
{
prop1: 88,
prop2: "Whatever",
prop3: "world",
prop4: "You get it",
},
]
创建一个或多个对象的子集可以通过这种方式解构对象来实现。
const sections = aListOfObjects.map(({prop1, prop2}) => ({prop1, prop2}));
两种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);
我添加这个答案,因为没有一个答案使用逗号操作符。
解构赋值和运算符很简单
Const对象= {a: 5, b: 6, c: 7}; Const selected = ({a,c} = object, {a,c}) console.log(选择);
补充另一种深奥的方法,这也很有效:
var obj = {a: 1, b:2, c:3}
var newobj = {a,c}=obj && {a,c}
// {a: 1, c:3}
但是你必须把道具名写两遍。