首页 > 解决方案 > 转换 javascript 对象

问题描述

JavaScript 对象的这种简单(和以前一样)转换让我失望。我想通过以下方式展平这个对象。

这就是我所拥有的:

{
    "1": {
        "group": "Clothes",
        "brand": {
            "0": {
                "brand_id": "12",
                "brand_name": "Adidas"
            },
            "1": {
                "brand_id": "15",
                "brand_name": "Zara"
            }
        }
    },
    "2": {
        "group": "Cars",
        "brand": {
            "0": {
                "brand_id": "43",
                "brand_name": "Ferrari"
            },
            "1": {
                "brand_id": "51",
                "brand_name": "BMW"
            }
        }
    }
}

这就是它,我想要得到的

{0: {
    brand_id: "12",
    brand_name: "Adidas",
    group: "Clothes",
}
1: {
    brand_id: "15",
    brand_name: "Zara",
    group: "Clothes",
},
2: {
    brand_id: "43",
    brand_name: "Ferrari",
    group: "Cars",
}
3: {
    brand_id: "51",
    brand_name: "BMW",
    group: "Cars",
}}

我尝试使用.reduce()or.map()但无效。

标签: javascriptarraystypescriptfor-loopfilter

解决方案


你可以做:

const data = {1: {group: 'Clothes',brand: [{0: {brand_id: '12',brand_name: 'Adidas'}},{1: {brand_id: '15',brand_name: 'Zara'}}]},2: {group: 'Cars',brand: [{0: {brand_id: '43',brand_name: 'Ferrari'}},{1: {brand_id: '51',brand_name: 'BMW'}}]}};
const result = {};

Object.keys(data).forEach(k => {
  data[k].brand.forEach((b, i) => {
    result[Object.keys(result).length] = {
      brand_id: b[i].brand_id,
      brand_name: b[i].brand_name,
      group: data[k].group
    };
  });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读