假设我有一个对象:

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

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

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

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

我怎样才能做到呢?


当前回答

在这个问题中,解构为动态命名的变量在JavaScript中是不可能的。

要动态设置键,可以使用reduce函数而不改变对象,如下所示:

const get子集= (obj,…keys) =>个key。Reduce ((a, c) =>({…A, [c]: obj[c]}), {}); Const elmo = { 颜色:红色, 讨厌:没错, 高度:“未知”, Meta: {1: '1', 2: '2'} } const子集= get子集(elmo, 'color', '烦人') console.log(子集)

应该注意的是,你是在每次迭代中创建一个新对象,而不是更新一个克隆。——mpen

下面是一个使用reduce和单个克隆的版本(更新传入的初始值以reduce)。

const get子集= (obj,…keys) =>个key。Reduce ((acc, curr) => { Acc [curr] = obj[curr] 返回acc }, {}) Const elmo = { 颜色:红色, 讨厌:没错, 高度:“未知”, Meta: {1: '1', 2: '2'} } const子集= get子集(elmo, '烦人','height', 'meta') console.log(子集)

其他回答

只是另一种方式……

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

var subset = [elmo].map(x => ({
  color: x.color,
  height: x.height
}))[0]

你可以在Objects =)数组中使用这个函数

动态解决方案

['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']));

我想在这里提到一个非常好的策展:

pick-es2019.js

Object.fromEntries(
  Object.entries(obj)
  .filter(([key]) => ['whitelisted', 'keys'].includes(key))
);

pick-es2017.js

Object.entries(obj)
.filter(([key]) => ['whitelisted', 'keys'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});

pick-es2015.js

Object.keys(obj)
.filter((key) => ['whitelisted', 'keys'].indexOf(key) >= 0)
.reduce((newObj, key) => Object.assign(newObj, { [key]: obj[key] }), {})

omit-es2019.js

Object.fromEntries(
  Object.entries(obj)
  .filter(([key]) => !['blacklisted', 'keys'].includes(key))
);

omit-es2017.js

Object.entries(obj)
.filter(([key]) => !['blacklisted', 'keys'].includes(key))
.reduce((obj, [key, val]) => Object.assign(obj, { [key]: val }), {});

omit-es2015.js

Object.keys(obj)
.filter((key) => ['blacklisted', 'keys'].indexOf(key) < 0)
.reduce((newObj, key) => Object.assign(newObj, { [key]: obj[key] }), {})

补充另一种深奥的方法,这也很有效:

var obj = {a: 1, b:2, c:3}
var newobj = {a,c}=obj && {a,c}
// {a: 1, c:3}

但是你必须把道具名写两遍。

你也可以使用Lodash。

var subset = _.pick(elmo ,'color', 'height');

作为补充,假设你有一个“elmo”数组:

elmos = [{ 
      color: 'red',
      annoying: true,
      height: 'unknown',
      meta: { one: '1', two: '2'}
    },{ 
      color: 'blue',
      annoying: true,
      height: 'known',
      meta: { one: '1', two: '2'}
    },{ 
      color: 'yellow',
      annoying: false,
      height: 'unknown',
      meta: { one: '1', two: '2'}
    }
];

如果你想要同样的行为,使用lodash,你只需要:

var subsets = _.map(elmos, function(elm) { return _.pick(elm, 'color', 'height'); });