假设我有一个对象:
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' }
我怎样才能做到呢?
当前回答
使用“with”语句的简写对象文字语法
还没有人演示过这种方法,可能是因为它很糟糕,你不应该这么做,但我觉得必须把它列出来。
Var o = {a:1,b:2,c:3,d:4,e:4,f:5} (o) { Var输出= {a,b,f} } console.log(输出)
利:你不需要输入两次属性名。
缺点:由于许多原因,不建议使用“with”语句。
结论:它很有效,但不要使用它。
其他回答
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");
我知道它不是最干净的,但它简单易懂。
function obj_multi_select(obj, keys){
let return_obj = {};
for (let k = 0; k < keys.length; k++){
return_obj[keys[k]] = obj[keys[k]];
};
return return_obj;
};
动态属性的解构赋值
这个解决方案不仅适用于你的具体例子,而且更普遍适用:
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等,以考虑更多的属性。
打印稿的解决方案:
function pick<T extends object, U extends keyof T>(
obj: T,
paths: Array<U>
): Pick<T, U> {
const ret = Object.create(null);
for (const k of paths) {
ret[k] = obj[k];
}
return ret;
}
输入信息甚至允许自动补全:
Credit to definitelytyping for U extends keyof T trick!
打印稿操场
你也可以使用Lodash。
var subset = _.pick(elmo ,'color', 'height');
作为补充,假设你有一个“elmo”数组:
elmos = [{
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
},{
color: 'blue',
annoying: true,
height: 'known',
meta: { one: '1', two: '2'}
},{
color: 'yellow',
annoying: false,
height: 'unknown',
meta: { one: '1', two: '2'}
}
];
如果你想要同样的行为,使用lodash,你只需要:
var subsets = _.map(elmos, function(elm) { return _.pick(elm, 'color', 'height'); });