假设我有一个对象:

elmo = { 
  color: 'red',
  annoying: true,
  height: 'unknown',
  meta: { one: '1', two: '2'}
};

我想用它的属性子集创建一个新对象。

 // pseudo code
 subset = elmo.slice('color', 'height')

 //=> { color: 'red', height: 'unknown' }

我怎样才能做到呢?


当前回答

还有一个解决方案:

var subset = {
   color: elmo.color,
   height: elmo.height 
}

到目前为止,这看起来比任何答案都更具可读性,但也许这只是我的想法!

其他回答

动态解决方案

['color', 'height'].reduce((a,b) => (a[b]=elmo[b],a), {})

让子集= (obj、钥匙)= > keys.reduce ((a, b) = > ([b] = obj [b], a), {}); / /测试 让elmo = { 颜色:红色, 讨厌:没错, 高度:“未知”, Meta: {1: '1', 2: '2'} }; Console.log(子集(elmo, ['color', 'height']));

核心库中没有这样的内置功能,但你可以使用对象解构来实现它…

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);

Try

const elmo={color:"red",annoying:!0,height:"unknown",meta:{one:"1",two:"2"}};

const {color, height} = elmo; newObject = ({color, height});

console.log(newObject); //{ 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”语句。

结论:它很有效,但不要使用它。