假设我有一个对象:
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' }
我怎样才能做到呢?
当前回答
虽然它有点啰嗦,但通过使用Array.prototype.reduce,你可以完成其他人在2年前推荐的underscore/lodash。
var subset = ['color', 'height'].reduce(function(o, k) { o[k] = elmo[k]; return o; }, {});
这种方法从另一方面解决了这个问题:而不是获取一个对象并将属性名传递给它来提取,而是获取一个属性名数组并将它们简化为一个新对象。
While it's more verbose in the simplest case, a callback here is pretty handy, since you can easily meet some common requirements, e.g. change the 'color' property to 'colour' on the new object, flatten arrays, etc. -- any of the things you need to do when receiving an object from one service/library and building a new object needed somewhere else. While underscore/lodash are excellent, well-implemented libs, this is my preferred approach for less vendor-reliance, and a simpler, more consistent approach when my subset-building logic gets more complex.
编辑:es7版本相同:
const subset = ['color', 'height'].reduce((a, e) => (a[e] = elmo[e], a), {});
编辑:这也是咖喱的一个很好的例子!让'pick'函数返回另一个函数。
const pick = (...props) => o => props.reduce((a, e) => ({ ...a, [e]: o[e] }), {});
上面的方法非常接近于另一种方法,除了它让你在运行中构建一个“picker”。如。
pick('color', 'height')(elmo);
这种方法的特别之处在于,你可以很容易地将所选的“picks”传递到任何带有函数的对象中,例如Array#map:
[elmo, grover, bigBird].map(pick('color', 'height'));
// [
// { color: 'red', height: 'short' },
// { color: 'blue', height: 'medium' },
// { color: 'yellow', height: 'tall' },
// ]
其他回答
这适用于我在Chrome控制台。有什么问题吗?
var { color, height } = elmo
var subelmo = { color, height }
console.log(subelmo) // {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");
如果你已经在使用lodash库的选择方法。
var obj = { 'a': 1, 'b': '2', 'c': 3 };
_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }
https://lodash.com/docs/4.17.10#pick
使用对象解构和属性简写
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)