【问题标题】:How to turn object values into new array in JavaScript如何在 JavaScript 中将对象值转换为新数组
【发布时间】:2020-03-17 19:56:35
【问题描述】:

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

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

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

【问题讨论】:

  • 所以数组映射是你需要的,我假设= 真的是:

标签: javascript arrays reactjs sorting object


【解决方案1】:

尝试使用地图

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

【讨论】:

    【解决方案2】:

    我认为这就是你想要的,你需要在循环中为你的数据集添加这个 sn-p 并将它推入一个新数组:

    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)

    【讨论】:

    • 非常感谢!这正是我所需要的。
    • 我是堆栈溢出的新手。我尝试支持你的帖子,但它说只为那些超过 15 名声望的人工作。我如何接受它作为答案?
    • 我为你的问题投票,你现在应该可以投票了:P,你也可以在箭头下方看到一个灰色的 ✔️ 图标,只需点击它即可接受答案。跨度>
    【解决方案3】:

    通过使用 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)
    

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2015-08-20
      • 2022-01-01
      • 1970-01-01
      • 2015-01-13
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      相关资源
      最近更新 更多