假设我有一个对象:

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

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

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

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

我怎样才能做到呢?


当前回答

我知道它不是最干净的,但它简单易懂。

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 {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,你可以完成其他人在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' },
// ]

两种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 object = { a: 5, b: 6, c: 7  };
const subset = (({ a, c }) => ({ a, c }))(object);
console.log(subset); // { a: 5, c: 7 }

扩展内置原型有其优势。如果你使用Object.defineProperty,你不会产生任何污染-唯一剩下的问题是与未来属性的冲突(例如,你定义Object.prototype。在将来,ES标准将Object.prototype.slice定义为具有不同的功能-现在您的代码正在破坏Object.prototype.slice中应该存在的预期功能)。

...... ....... ...... .....Elmo的身高不是未知的(!!)

Object.defineProperty(Object.prototype, 'slice', { 可列举的:假的, 可写:没错, 值:function(…args) { 让o = {}; for (let k of args) this. hasownproperty (k) && (o[k] = this[k]); 返回啊; } }); Elmo = { 颜色:红色, 讨厌:没错, 高度:“24”, Meta: {1: '1', 2: '2'} }; console.log(艾尔摩。片(“颜色”、“高度”)); console.log('看,没有污染:); 对于(let k in elmo) console.log(' - ${k} ');