[英]Create new object based on filtered keys
假設我有一個表示鍵的字符串數組,例如['a', 'b', 'd']
和一個現有的對象,例如...
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
}
是否有一種基於數組中的鍵創建新對象的方法,該對象是obj
的篩選版本,因此...
const updated = {
a: 1,
b: 2,
d: 4
}
使用Object.assign()
函數?
我知道它可以與...
function createNew(o, keys) {
const updated = {}
Object.keys(o).forEach(k => {
if (keys.includes(k)) updated[k] = o[k]
})
return updated
}
但我正在尋找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.