我將如何動態更新物件陣列中的鍵?
我有以下名為 headers 的字串陣列:
headers = ['col1', 'col2', 'col3', 'col4']
我有一個名為行的物件陣列:
const rows = [
{
column1: 'value1',
column2: 'value2',
column3: 'value3',
column4: 'value4'
},
{
column1: 'value5',
column2: 'value6',
column3: 'value7',
column4: 'value8'
}
];
我想更新行內的鍵,以便它與動態完成的標題的值相匹配,而無需對其進行硬編碼。
預期輸出為字串陣列:
{
col1: 'value1',
col2: 'value2',
col3: 'value3',
col4: 'value4'
},
{
col1: 'value5',
col2: 'value6',
col3: 'value7',
col4: 'value8'
}
uj5u.com熱心網友回復:
如果您在理解任何部分時遇到困難,請告訴我
function convertKeys(array , newKeys){
return array.map(row=>{
return Object.fromEntries(Object.entries(row).map((x,i)=> {
x[0] =headers[i]
return x
}))
})
}
convertKeys(rows,headers)
或者你可以使用這樣的東西而不是依賴順序
let newKeys = [
["column1", "col1"],
["column2", "col2"],
["column3", "col3"],
["column4", "col4"],
]
function convertKeys(array , newKeys){
array.forEach(obj=>{
for (let i = 0 ; i < newKeys.length ; i ){
let [oldKey,newKey] = newKeys[i]
if(obj.hasOwnProperty(oldKey)){
obj[newKey] = obj[oldKey]
delete obj[oldKey]
}
}
})
return array
}
convertKeys(rows,newKeys)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318001.html
標籤:javascript 数组 目的
下一篇:根據匿名物件訪問限制器的實作方法
