Suppose I have an array of strings that represent keys such as ['a', 'b', 'd']
, and an existing object such as...
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...
const updated = {
a: 1,
b: 2,
d: 4
}
using the Object.assign()
function?
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()
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.