Javascript-使用数组中的键复制对象

时间:2019-06-18 08:02:20

标签: javascript

我有一个名称在其中的数组。

我还有一个对象,其键与数组中的键相同。该对象还具有其他键。

我想复制对象,但只包含数组中的键

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)

9 个答案:

答案 0 :(得分:3)

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)

答案 1 :(得分:3)

尝试一下:

const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}

const extract = ({one, two, three}) =>Object.assign({},{one, two, three});

console.log(extract(obj))

答案 2 :(得分:2)

使用forEach循环

const keys = ['one', 'two', 'three'];

const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}
var obj1={};
keys.forEach(e=>{
obj1[e]=obj[e]
})
const objCopy = Object.assign({}, obj1)
console.log(objCopy)

答案 3 :(得分:2)

非常简单的reduce

const keys = ['one', 'two', 'three'];

const obj = {
  date: 'Jan',
  color: 'Red',
  one: 367,
  two: 427,
  three: 753
};

const res = keys.reduce((a, c) => (obj[c] ? a[c] = obj[c] : c, a), {});
console.log(res);

(三元运算符可确保该键实际上存在于对象中-否则,您将不得不过滤掉结果中的undefined)。

答案 4 :(得分:2)

可以通过以下方式获取所需对象:

const keys = ['one', 'two', 'three'];

const obj = {
    date: 'Jan',
    color: 'Red',
    one: 367,
    two: 427,
    three: 753
}

let desiredObject = Object.keys(obj)
    .filter(key => keys.includes(key))
    .map(key => {
        return {[key]: obj[key]}
    })
    .reduce((a, b) => Object.assign({}, a,b));

答案 5 :(得分:1)

这可能对您有帮助,您必须遍历keys数组并添加obj中的每个现有键,以构造新对象。这不是副本,而是具有所需键的新对象。

const keys = ['one', 'two', 'three'];

const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}

const objCopy = {};

for (let i = 0; i < keys.length; i++) {
  objCopy[keys[i]] = obj[keys[i]];
}

console.log(objCopy)

您不需要使用任何其他精美的方法来执行此操作,其他方法的确会减少代码行的数量,但会降低性能,例如使用.reduce()或其他Array方法

答案 6 :(得分:1)

您可以在keys数组上使用.reduce来获取所需的对象。

const keys = ['one', 'two', 'three'];

const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}

const objCopy = keys.reduce((a,e) => {
  a[e] = obj[e];
  return a;
}, {});

console.log(objCopy)

答案 7 :(得分:1)

cont objCopy = Object.entries(obj).reduce(([key, value],acc)=>keys.includes(key)?{...acc, key:value}:acc, {}) 

答案 8 :(得分:1)

hasOwnProperty用于排除继承的属性

const keys = ['one', 'two', 'three'];

const obj = {
  date: 'Jan',
  color: 'Red',
  one: 367,
  two: 427,
  three: 753
}

const objCopy = {}; // copy

for (let property in obj) {
  if (obj.hasOwnProperty(property) && keys.find(k => k == property)) {
    objCopy[property] = obj[property];
  }
}

console.log(objCopy);