假设我有一个对象:
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 object = { a: 5, b: 6, c: 7 };
const subset = (({ a, c }) => ({ a, c }))(object);
console.log(subset); // { a: 5, c: 7 }
其他回答
核心库中没有这样的内置功能,但你可以使用对象解构来实现它…
const {color, height} = sourceObject;
const newObject = {color, height};
你也可以写一个效用函数…
const cloneAndPluck = function(sourceObject, keys) {
const newObject = {};
keys.forEach((obj, key) => { newObject[key] = sourceObject[key]; });
return newObject;
};
const subset = cloneAndPluck(elmo, ["color", "height"]);
像Lodash这样的库也有_.pick()。
两种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 = (({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)
我认为这就是你的答案。(以及所有正在寻找它的人)。
const object = { a: 5, b: 6, c: 7 };
const subset = (({ a, c }) => ({ a, c }))(object);
console.log(subset); // { a: 5, c: 7 }
使用“with”语句的简写对象文字语法
还没有人演示过这种方法,可能是因为它很糟糕,你不应该这么做,但我觉得必须把它列出来。
Var o = {a:1,b:2,c:3,d:4,e:4,f:5} (o) { Var输出= {a,b,f} } console.log(输出)
利:你不需要输入两次属性名。
缺点:由于许多原因,不建议使用“with”语句。
结论:它很有效,但不要使用它。