簡體   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