创建一个子对象,只包含现有对象的一些属性 [英] Create a subset object, consisting of only some of the properties of an existing object

查看:87
本文介绍了创建一个子对象,只包含现有对象的一些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个例子最好的解释。以下作品在es6中创建一个由现有对象的一些键组成的对象:

  var o = {a:1,b:2,c:3} 
var {a,c} = o
var subsetObj = {a,c} //将是:{a: 1,c:3}

这里有两个缺点:


  1. 它需要两条命令,两条线来创建所需的子集对象

  2. 我们必须通过创建本地变量范围来污染本地变量范围中间人 a c 变量,这些变量不需要在本地,除非是创建我们的子集对象的手段。 / li>

有没有办法在单个语句中完成相同的事情,而不会引入不必要的本地人 a c

解决方案

这个的语法。你可以继续做:

  var subsetObj = {a:o.a,c:o.c}; 

如果您有更多属性或可变数量的属性,请创建一个帮助函数。

相关:是否可以重建到现有对象? (Javascript ES6)


This is best explained by example. The following works in es6 to create an object consisting of some of the keys of an existing object:

var o = {a:1, b: 2, c: 3}
var {a, c} = o
var subsetObj = {a, c} // will be: {a:1, c:3}

There are two downsides here:

  1. It took two statments, and two lines, to create the desired subset object
  2. We had to pollute the local variable scope by creating the intermediary a and c variables, which aren't needed locally, except as a means to creating our subset object.

Is there a way to accomplish the same thing in a single statement, without introducing the unnecessary locals a and c?

解决方案

There is no specific syntax for this. You can keep doing:

var subsetObj = {a: o.a, c: o.c};

If you have more properties or a variable number of properties, create a helper function.

Related: Is it possible to destructure onto an existing object? (Javascript ES6)

这篇关于创建一个子对象,只包含现有对象的一些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆