繁体   English   中英

使用 Javascript 将 object 转换为数组格式

[英]Converting object to array format with Javascript

我有这样的数据 object :

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

我想将格式更改为:

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

如何使用 javascript 实现它?

你可以这样做:

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

let newArray = [];

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

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

 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);

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

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM