亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 JavaScript 中對數組進行過濾后構造一個對象數組

在 JavaScript 中對數組進行過濾后構造一個對象數組

胡說叔叔 2023-02-24 11:08:56
我能夠過濾數組,但是當我嘗試從過濾后的數據中創建對象數組時,結果似乎是undefined. 如何構建以下格式的對象數組。有人可以幫忙嗎?[{ brand: 'BMW'}, { brand: 'Audi'}]片段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)
查看完整描述

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);


查看完整回答
反對 回復 2023-02-24
?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

如果你想從箭頭函數返回一個對象字面量,你需要將該對象字面量括在圓括號中以區別于代碼塊,代碼塊也恰好用花括號括起來:


result = cars.map(car => ({

  brand: car.name

}));

有趣的是您的代碼沒有導致錯誤。只是因為 JavaScript 中有標簽語法,所以箭頭函數中的代碼基本上會創建一個brand標簽到松散值car.name.


查看完整回答
反對 回復 2023-02-24
?
茅侃侃

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)


查看完整回答
反對 回復 2023-02-24
?
忽然笑

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)


查看完整回答
反對 回復 2023-02-24
  • 4 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號