使用 Javascript 将对象转换为数组格式
Converting object to array format with Javascript
我有一个这样的数据对象:
{
"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] });
});
如果对象不是动态的,这可能有效。
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);
我有一个这样的数据对象:
{
"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] });
});
如果对象不是动态的,这可能有效。
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);