如何在 JavaScript 中将对象值转换为新数组

我正在尝试简化以下状态:


  "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 个的数组。并非每个对象都包含两种类型;有些只包含一个。


我相信这是我迄今为止尝试过的大部分方法都不起作用的原因。预先感谢您的帮助。


慕容森
浏览 208回答 3
3回答

catspeake

我认为这就是您想要的,您需要在循环中为您的数据集添加此代码段并将其推送到新数组中: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)

心有法竹

尝试使用地图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);

UYOU

通过使用 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript