如何将数组转换为新数组?

问题描述 投票:0回答:1

我有一个像这样的数组:

    var categories = [
        {
            "info": {"id": 1, "title": "cat1"},
            "products": [{"id": "1a", "title": "prod1"}, {"id": "1b", "title": "prod2"}]
        },
        {
            "info": {"id": 2, "title": "cat2"},
            "products": [{"id": "2a", "title": "prod3"}, {"id": "2b", "title": "prod4"}]
        },
        {
            "info": {"id": 3, "title": "cat3"},
            "products": [{"id": "3a", "title": "prod5"}, {"id": "3b", "title": "prod6"}]
        }
    ]

我想将这些数据转换成这样:

var categoriesNew = [
        {
            "id": 1,
            "title": "cat1",
            "products": [{"id": "1a", "title": "prod1"}, {"id": "1b", "title": "prod2"}]
        },
        {
            "id": 2,
            "title": "cat2",
            "products": [{"id": "2a", "title": "prod3"}, {"id": "2b", "title": "prod4"}]
        },
        {
            "id": 3,
            "title": "cat3",
            "products": [{"id": "3a", "title": "prod5"}, {"id": "3b", "title": "prod6"}]
        }
    ]

我已经尝试过这段代码:

var categoriesNew = []
for(var i=0; i<categories[i].length; i++) {
    categoriesNew.push(categories[i].info)
    categoriesNew.push(categories[i].products)
}

但它没有提供我所需的输出。如何解决这个问题?

javascript arrays javascript-objects
1个回答
0
投票

您的代码没有创建对象。

在您的情况下,创建新对象数组的最简单方法是地图

const newCategories = categories.map(({ info, products }) => ({
  id:  info.id, 
  title: info.title,
  products
}))
console.log(newCategories);
<script>
  const categories = [{
      "info": {
        "id": 1,
        "title": "cat1"
      },
      "products": [{
        "id": "1a",
        "title": "prod1"
      }, {
        "id": "1b",
        "title": "prod2"
      }]
    },
    {
      "info": {
        "id": 2,
        "title": "cat2"
      },
      "products": [{
        "id": "2a",
        "title": "prod3"
      }, {
        "id": "2b",
        "title": "prod4"
      }]
    },
    {
      "info": {
        "id": 3,
        "title": "cat3"
      },
      "products": [{
        "id": "3a",
        "title": "prod5"
      }, {
        "id": "3b",
        "title": "prod6"
      }]
    }
  ]
</script>

© www.soinside.com 2019 - 2024. All rights reserved.