我有一个包含名称的数组。
我还有一个对象,其键与数组中的键相同。该对象还有其他键。
我想复制对象,但只包含数组中的键
const keys = ['one', 'two', 'three'];
const obj = {
date: 'Jan',
color: 'Red',
one: 367,
two: 427,
three: 753
}
const objCopy = Object.assign({}, obj)
// I'd like this console to display
// {
// "one": 367,
// "two": 427,
// "three": 753
// }
console.log(objCopy)
最佳答案
const keys = ['one', 'two', 'three'];
const obj = {
date: 'Jan',
color: 'Red',
one: 367,
two: 427,
three: 753
}
const objCopy = {};
keys.forEach(key => objCopy[key] = obj[key]);
console.log(objCopy)
关于Javascript - 使用数组中的键复制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644421/