假设我有一个对象:

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

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

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

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

我怎样才能做到呢?


当前回答

只是另一种方式……

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 =)数组中使用这个函数

其他回答

如果你想保留比你想删除的属性更多的属性,你可以使用rest参数语法:

const obj = {
  a:1,
  b:2,
  c:3,
  d:4
};
const { a, ...newObj } = obj;
console.log(newObj); // {b: 2, c: 3, d: 4}

如果你正在使用ES6,有一种非常简洁的方法来使用解构来做到这一点。析构允许您轻松地使用扩展添加到对象,但它也允许您以相同的方式创建子集对象。

const object = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
}

// Remove "c" and "d" fields from original object:
const {c, d, ...partialObject} = object;
const subset = {c, d};

console.log(partialObject) // => { a: 'a', b: 'b'}
console.log(subset) // => { c: 'c', d: 'd'};

你可以使用逗号操作符

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

const subset = ({color , height} = elmo , {color , height});
// {color: 'red', height: 'unknown'}

将参数转换为数组 使用Array.forEach()来选择属性 Object.prototype.pick = function(…args) { Var obj = {}; arg游戏。forEach(k => obj[k] = this[k]) 返回obj } Var a = {0:"a",1:"b",2:"c"} var b = a.pick(' 1 ', ' 2 ') / /输出将{1:“b”,2:“c”}

你也可以使用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'); });