简体   繁体   English

使用另一个对象的属性子集获取对象

[英]Get object with a subset of properties of another object

I am aware of this existing question however I am interested in only plain javascript solutions (with no external libs like lodash). 我知道这个现有的问题,但我只对普通的javascript解决方案感兴趣(没有像lodash这样的外部库)。

What would be the cleanest way (including all ES6 goodness and beyond - like object rest & spread etc.) to get an object with a subset of props from another object in javascript? 什么是最干净的方式 (包括所有ES6的善良和超越 - 如对象休息和传播等)从javascript中获取具有来自另一个对象的道具子集的对象?

Lets say I want to pick foo , bar , and baz from source object. 让我们说我想从source对象中选择foobarbaz I currently have two solutions, I like neither of them: 我目前有两个解决方案,我不喜欢它们:

1. 1。

const result = {
  foo: source.foo,
  bar: source.bar,
  baz: source.baz
};

2. 2。

const { foo, bar, baz } = source;
const target = { foo, bar, baz };

The second one is shorter but it pollutes current execution scope with some variables and the list of them has to be written twice anyway. 第二个是较短但是它用一些变量污染了当前的执行范围,并且它们的列表无论如何都必须写入两次。

PS. PS。 I am also not interested in augmenting Object.prototype with some helper method or calling some custom function to achieve this. 我也Object.prototype用一些辅助方法扩充Object.prototype或调用一些自定义函数来实现这一点。

You could use an IIFE with a destruction. 你可以使用具有破坏性的IIFE。

 const source = { foo: 1, bar: 2, baz: 3 }, target = (({ foo, bar, baz }) => ({ foo, bar, baz }))(source); console.log(target); 

If you've got an object that contains many properties you need, and and a small amount you don't, you can use the object rest syntax : 如果你有一个包含你需要的许多属性的对象,而你有一些不需要的属性,你可以使用对象rest语法

 const source = { foo: 1, bar: 2, baz: 3, whatever: 4 }; const { whatever, ...target } = source; console.log(target); 

Note - Object rest is aa Stage 3 proposal for ECMAScript, and a transpiler (babel with the Object rest spread transform ) is needed. - 对象休息是ECMAScript的第3阶段提议,需要一个转换器(带有Object rest spread变换的 babel)。

You can use destructuring assignment 您可以使用解构分配

 const source = {foo: 1, bar:2, baz:3, abc: 4, def: 5}; const result = {}; ({foo:result.foo, bar:result.bar, baz:result.baz} = source); console.log(result); 

Alternatively you can set property names as elements of an array, use for..of loop with destructuring assignment to set properties, values of target 或者,您可以将属性名称设置为数组的元素,使用带有解构赋值的for..of循环来设置属性, target

 const source = {foo: 1, bar:2, baz:3, abc:4, def: 5}; const result = {}; for (let prop of ["foo", "bar", "baz"]) ({[prop]:result[prop]} = source); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM