简体   繁体   English

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

[英]Converting object to array format with Javascript

I have a data object like this:我有这样的数据 object :

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

I want to change the format to be like this:我想将格式更改为:

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

how to achieve it using javascript?如何使用 javascript 实现它?

You could do this:你可以这样做:

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

let newArray = [];

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

This could work if the object is not dynamic.如果 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);

You can do it like this: Note that the array's length may not be equal, so it is best to consider this in your data conversion routine.您可以这样做:请注意,数组的长度可能不相等,因此最好在您的数据转换例程中考虑这一点。

 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