【问题标题】:How to flatten an array inside of an object?如何展平对象内部的数组?
【发布时间】:2019-11-26 12:19:26
【问题描述】:

基本上,我想使用 Javascript(最好是 ES6)在对象内部展平一个数组。我实际上不确定这是否甚至是扁平化的问题,我只是想要一个很好的方法来进行这种更改。

我想从这里开始:

{
  id: "123",
  name: "test",
  history: [
    {
      id: "456",
      name: "test2"
    },
    {
      id: "789",
      name: "test3"
    }
  ]
}

到这里……

{
  id: "123",
  name: "test"
},
{
  id: "456",
  name: "test2"
},
{
  id: "789",
  name: "test3"
}

基本上在原始对象中,我有一个与该特定对象相关的“历史”属性。有什么想法吗?

【问题讨论】:

  • 能否请您附上您解决此问题的尝试?
  • 生成的结构无效
  • history 中的对象本身可以有history 数组吗?换句话说,这可以无限嵌套吗?

标签: javascript arrays json object flatten


【解决方案1】:

您可以使用解构和休息语法,将历史记录和第一个对象分开,然后将它们组合成一个具有展开或连接的数组。

const { history, ...obj1 } = {"id":"123","name":"test","history":[{"id":"456","name":"test2"},{"id":"789","name":"test3"}]}

const result = [obj1, ...history]

console.log(result)

【讨论】:

    【解决方案2】:

    试试这个:

     const data =  {
      "id": "123",
      "name": "test",
      "history": [
        {
          "id": "456",
          "name": "test2"
        },
        {
          "id": "789",
          "name": "test3"
        }
      ]
    }
    
    const  {id, name, history} =  data ;
    const result  = [{id, name} , ...history];
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 2020-05-18
      • 2019-09-26
      • 2021-11-06
      相关资源
      最近更新 更多