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

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

如何在 JavaScript 中將對象值轉換為新數組

如何在 JavaScript 中將對象值轉換為新數組

慕容森 2022-05-22 10:30:23
我正在嘗試簡化以下狀態:{   "name": "bulbasaur",   "picture": "https://raw",   "height": 7,   "weight": 69,   "types": [    {       "slot": 1,      "type": {         "name": "poison",         "url": "https://poke"       }    },     {       "slot": 2,       "type": {         "name": "grass",         "url": "https://poke"       }    }]}變成這樣的東西:{   "name": "bulbasaur",   "picture": "https://raw",   "height": 7,   "weight": 69,   "types": [ "poison", "grass" ] }另外,我想提一下,我有一個包含 151 個的數組。并非每個對象都包含兩種類型;有些只包含一個。我相信這是我迄今為止嘗試過的大部分方法都不起作用的原因。預先感謝您的幫助。
查看完整描述

3 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

我認為這就是您想要的,您需要在循環中為您的數據集添加此代碼段并將其推送到新數組中:


const Obj = { 

  "name": "bulbasaur", 

  "picture": "https://raw", 

  "height": 7, 

  "weight": 69, 

  "types" : [{ 

    "slot": 1, 

    "type": { 

      "name": "poison", 

      "url":"https://poke" 

  }}, { 

    "slot": 2, 

    "type": { 

      "name": "grass", 

        "url":"https://poke" 

    }}

]};


const newObj = {

  ...Obj,

  types: Obj.types.map((el) => el.type.name),

}


console.log(newObj)


查看完整回答
反對 回復 2022-05-22
?
心有法竹

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

嘗試使用地圖


let obj={ name: "bulbasaur", picture: "https://raw", height: 7, weight: 69, types : [{ slot: 1, type: { name: "poison", url:"https://poke" }}]};

obj.types=obj.types.map( Type => Type.type.name);

console.log(obj.types);


查看完整回答
反對 回復 2022-05-22
?
UYOU

TA貢獻1878條經驗 獲得超4個贊

通過使用 Ma'moun othman 提供的邏輯,我能夠解決我需要的問題。


  "name": "bulbasaur", 

  "picture": "https://raw", 

  "height": 7, 

  "weight": 69, 

  "types" : [{ 

    "slot": 1, 

    "type": { 

        "name": "poison", 

        "url":"https://poke" 

    }}, { 

    "slot": 2, 

    "type": { 

        "name": "grass", 

        "url":"https://poke" 

    }}

]};


const newObj = {

  ...Obj,

  types: Obj.types.map((el) => el.type.name),

}


console.log(newObj)


查看完整回答
反對 回復 2022-05-22
  • 3 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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