json 将具有属性的数组转换为列表

im9ewurl  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(137)

我正在使用一个图形库,操作来自API的数据非常糟糕。问题是图表库不接受我正在使用的API返回的数据格式。
API响应

const data = [
  {
      "house01": {
        "free": 6
      },
      "house02": {
        "free": 2
      },
      "house03": {
        "free": 1
      },
  }
]

字符串
预期(已验证)

const data = [
          {
            "label": "house01"
            "free": 6
          },
          {
            "label": "house02"
            "free": 2
          },
          {
            "label": "house03"
            "free": 1
          },
    ]

vm0i2vca

vm0i2vca1#

你在找这个吗?

const data = [
  {
    house01: {
      free: 6
    },
    house02: {
      free: 2
    },
    house03: {
      free: 1
    }
  }
];

const expectedData = Object.entries(data[0]).map(d => ({
  label: d[0],
  free: d[1].free
}));

console.log(expectedData)

const data2 = {
  house01: { free: 6 },
  house02: { free: 2 },
  house03: { free: 1 }
};

const expectedData2 = Object.entries(data2).map(d => ({
  label: d[0],
  free: d[1].free
}));

console.log(expectedData2);

字符串

7vhp5slm

7vhp5slm2#

const data = [{
  "house01": {
    "free": 6
  },
  "house02": {
    "free": 2
  },
  "house03": {
    "free": 1
  },
}]
final = [];
temp = {};
Object.entries(data[0]).forEach(student => {
  temp.label = student[0];
  Object.entries(student[1]).forEach(student1 => {
    temp[student1[0]] = student1[1];
  })
  final.push(temp);
});
console.log(final);

字符串

相关问题