[英]Create new object based on filtered keys
Suppose I have an array of strings that represent keys such as ['a', 'b', 'd']
, and an existing object such as... 假设我有一个表示键的字符串数组,例如
['a', 'b', 'd']
和一个现有的对象,例如...
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
}
Is there a method of creating a new object that is a filtered version of obj
based on the keys in the array such that... 是否有一种基于数组中的键创建新对象的方法,该对象是
obj
的筛选版本,因此...
const updated = {
a: 1,
b: 2,
d: 4
}
using the Object.assign()
function? 使用
Object.assign()
函数?
I know it works with a function such as... 我知道它可以与...
function createNew(o, keys) {
const updated = {}
Object.keys(o).forEach(k => {
if (keys.includes(k)) updated[k] = o[k]
})
return updated
}
but I'm looking for a solution with Object.assign()
但我正在寻找
Object.assign()
的解决方案
const obj = { a: 1, b: 2, c: 3, d: 4, e: 5 }; const desiredKeys = ['a', 'c', 'd']; const result = desiredKeys.reduce((acc, key) => { acc[key] = obj[key]; return acc; }, {}); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.