假设我有一个对象:
elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
我想用它的属性子集创建一个新对象。
// pseudo code
subset = elmo.slice('color', 'height')
//=> { color: 'red', height: 'unknown' }
我怎样才能做到呢?
假设我有一个对象:
elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
我想用它的属性子集创建一个新对象。
// pseudo code
subset = elmo.slice('color', 'height')
//=> { color: 'red', height: 'unknown' }
我怎样才能做到呢?
当前回答
你可以使用逗号操作符
const elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
const subset = ({color , height} = elmo , {color , height});
// {color: 'red', height: 'unknown'}
其他回答
我认为这就是你的答案。(以及所有正在寻找它的人)。
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} ');
如何:
function sliceObj(obj) {
var o = {}
, keys = [].slice.call(arguments, 1);
for (var i=0; i<keys.length; i++) {
if (keys[i] in obj) o[keys[i]] = obj[keys[i]];
}
return o;
}
var subset = sliceObj(elmo, 'color', 'height');
你也可以使用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'); });
Try
const elmo={color:"red",annoying:!0,height:"unknown",meta:{one:"1",two:"2"}};
const {color, height} = elmo; newObject = ({color, height});
console.log(newObject); //{ color: 'red', height: 'unknown' }