4 回答

TA貢獻1829條經驗 獲得超7個贊
基本上,您需要將對象括在括號中以將其與塊語句區分開來。
const
cars = [{ name: 'BMW', type: 'Sedan' }, { name: 'Audi', type: 'SUV' }, { name: 'BMW', type: 'SUV' }],
result = cars
.filter(({ type }) => type === 'SUV')
.map(({ name: brand }) => ({ brand }));
// ^^^^^^^^^^^ wrap it
console.log(result);

TA貢獻1765條經驗 獲得超5個贊
如果你想從箭頭函數返回一個對象字面量,你需要將該對象字面量括在圓括號中以區別于代碼塊,代碼塊也恰好用花括號括起來:
result = cars.map(car => ({
brand: car.name
}));
有趣的是您的代碼沒有導致錯誤。只是因為 JavaScript 中有標簽語法,所以箭頭函數中的代碼基本上會創建一個brand標簽到松散值car.name.

TA貢獻1842條經驗 獲得超22個贊
您在 map 函數隱式返回的新對象周圍缺少一對括號。這是 es6 的一個棘手的語法。
const cars = [{
name: 'BMW',
type: 'Sedan'
}, {
name: 'Audi',
type: 'SUV'
}, {
name: 'BMW',
type: 'SUV'
}]
const result = cars.filter(({
type
}) => type === 'SUV').map((car) => ({
brand: car.name
}))
console.log(result)

TA貢獻1806條經驗 獲得超5個贊
為此,您可以聲明一個變量并將其返回。
const cars = [{
name: 'BMW',
type: 'Sedan'
}, {
name: 'Audi',
type: 'SUV'
}, {
name: 'BMW',
type: 'SUV'
}]
const result = cars.filter(({
type
}) => type === 'SUV').map((car) => {
let obj = {brand: car.name}
return obj
})
console.log(result)
添加回答
舉報