【问题标题】:Converting object to array format with Javascript使用Javascript将对象转换为数组格式
【发布时间】:2021-01-12 11:28:51
【问题描述】:

我有一个这样的数据对象:

{
  "backgroundColor": [
    "#E5700F",
    "#DA830F",
  ],
  "data": [
    26,
    10,
  ],
}

我想把格式改成这样:

[
{
"backgroundColor": "#E5700F",
"data": 26,},
{
"backgroundColor": "#DA830F",
"data": 10,},
]

如何使用javascript实现它?

【问题讨论】:

标签: javascript arrays object data-conversion


【解决方案1】:

你可以这样做:

const old = {
  backgroundColor: ["#E5700F", "#DA830F"],
  data: [26, 10],
};

let newArray = [];

old.backgroundColor.forEach((item, idx) => {
  newArray.push({ backgroundColor: item, data: old.data[idx] });
});

【讨论】:

    【解决方案2】:

    如果对象不是动态的,这可能会起作用。

    let data = {
      "backgroundColor": [
        "#E5700F",
        "#DA830F",
      ],
      "data": [
        26,
        10,
      ],
    };
    
    let result = data.backgroundColor.map(function(item, index) {
      return {
        backgroundColor: item,
        data: data.data[index]
      }
    });
    
    console.log(result);

    【讨论】:

      【解决方案3】:

      你可以这样做: 请注意,数组的长度可能不相等,因此最好在数据转换例程中考虑这一点。

      let sourceData = {
          "backgroundColor": [
              "#E5700F",
              "#DA830F",
          ],
          "data": [
              26,
              10,
          ],
      };
      
      let result = [];
      let length = Math.max(sourceData.backgroundColor.length, sourceData.data.length);
      
      for (let index = 0; index < length; index++) {
          result.push({
              "backgroundColor": sourceData.backgroundColor[index],
              "data": sourceData.data[index]
          })
      }
      
      console.log(result);

      【讨论】:

        猜你喜欢
        • 2021-08-21
        • 2021-01-09
        • 1970-01-01
        • 2019-10-22
        • 1970-01-01
        • 2020-10-18
        • 2018-07-14
        • 2015-02-25
        • 1970-01-01
        相关资源
        最近更新 更多