這應該很簡單,但我絆倒了它。
我有的:
{
notSet: 2,
set: 9,
blanks: 4,
other: 8
}
進入:
{
newKey: 6, (combine notSet and blanks remove them)
set: 9,
other: 8
}
uj5u.com熱心網友回復:
你可以這樣做
const obj = {
notSet: 2,
set: 9,
blanks: 4,
other: 8
}
const transform = ({notSet, blanks, ...rest}) => ({
...rest,
newKey: notSet blanks
})
const newObject = transform(obj)
console.log(newObject)
uj5u.com熱心網友回復:
使用 delete 關鍵字和一些檢查是可能的。您可能想洗掉多余的密鑰。
我使用了??( nullish coalescing operator ) 因為某些鍵可能不存在,并且使用0值更安全,否則您可能會得到NaN(如果您嘗試null/undefined使用 a添加number):
const obj1 = {
notSet: 2,
set: 9,
blanks: 4,
other: 8
};
const transformObj = (obj1) => {
obj1.newKey = (obj1.notSet ?? 0) (obj1.blanks ?? 0);
delete obj1.notSet;
delete obj1.blanks;
};
transformObj(obj1);
console.log(obj1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487491.html
標籤:javascript 目的
