4 回答

TA貢獻1858條經驗 獲得超8個贊
那 ?
const arr =
[ { id: 123, val: 'abcd', other: 'abcd' }
, { id: 123, val: 'abcd', other: 'abcd', show: true }
, { id: 123, val: 'abcd', other: 'abcd', show: false }
, { id: 123, val: 'abcd', other: 'abcd' }
]
const newArr = arr.map(({id,val,show})=>show?{id,val,show}:{id,val})
console.log( newArr )
.as-console-wrapper { max-height: 100% !important; top: 0; }

TA貢獻1789條經驗 獲得超8個贊
你可以像這樣重寫它。使用這種語法,當item.show括號為真時,您將解析為和對象,然后您只需將其傳播到您的對象中。您還可以使用無效合并來分配item.val
const expectedArr = arr.map((item) => ({
id: item.id,
val: item.val ?? "",
...(item.show && { show: item.show }),
}));

TA貢獻1877條經驗 獲得超1個贊
目前,它在函數內部的一行中包含多個條件,Array.map并且無效。
const arr = [{id: 123, val: 'abcd', other: 'abcd'}, {id: 123, val: 'abcd', other: 'abcd', show: true}, {id: 123, val: 'abcd', other: 'abcd', show: false}, {id: 123, val: 'abcd', other: 'abcd'}]
const result = arr.map(({ id, val, show }) => {
const newObj = {
id,
val: val != null ? val : ''
};
if (show) {
newObj['show'] = show;
}
return newObj;
});
console.log(result);

TA貢獻1875條經驗 獲得超5個贊
const arr = [{id: 123, val: 'abcd', other: 'abcd'}, {id: 123, val: 'abcd', other: 'abcd', show: true}, {id: 123, val: 'abcd', other: 'abcd', show: false}, {id: 123, val: 'abcd', other: 'abcd'}]
const expectedArr = arr.map(item => ({id: item.id, val: item.val? item.val: '', show: item.show? item.show: 0}))
console.log(expectedArr); //solved-ish
//but honestly, that's the furthest i can go with your strange code golfed syntax setup.. to be honest, using ? is similar to if but NOT if, it's closer to || but anyway
console.log('skip what was above, the moment of truth below')
const theRealAnswer = arr.map(item=>{ const i={id: item.id, val: item.val? item.val: '', show: item.show? item.show: 0};if(!i.show){delete(i.show)}return(i) })
console.log(theRealAnswer)
//now, the logical construct(what u gave the mapper) was impossible to do what u wanted. coding isn't just syntax, it's logic too. you cannot assign a key to completely delete the key itself
添加回答
舉報