我是Javascript的新手。我想从我的API数据中创建这样的数组。 这就是我想要的。
let consumptionDay2 = [
{
data: [
{ x: "0", y: 33 },
{ x: "1", y: 55 },
{ x: "2", y: 66 },
{ x: "3", y: 550 },
{ x: "4", y: 23 },
{ x: "5", y: 346 },
{ x: "6" ,y: 56 },
{ x: "7", y: 87 },
{ x: "8", y: 675 },
{ x: "9", y: 432 },
{ x: "10", y: 234 },
{ x: "11", y: 765 }
]
}
]
这就是我尝试过的。
let tempLineChart = []
let LineChartData;
for (j = 0; j < consumptionData.length; j++) {
let tempconsumptionData = {}
tempconsumptionData["x"] = consumptionData[j].time
tempconsumptionData["y"] = consumptionData[j].powerFactor
tempLineChart.push(tempconsumptionData)
}
LineChartData= {data: tempLineChart};
lineChart.push(LineChartData)
有人可以帮我把它作为上面的模型。
答案 0 :(得分:0)
按照您的代码并假设您的输入,这应该有效:
let result = [];
let lineChartData = {
data: consumptionData.map(item => ({
x: item.time,
y: item.powerFactor
}));
};
result.push(lineChartData)
答案 1 :(得分:0)
如果我不得不猜(和我一样),你需要像
这样的东西
// just guessing here
const consumptionData = [{"time":"0","powerFactor":33},{"time":"1","powerFactor":55},{"time":"2","powerFactor":66},{"time":"3","powerFactor":550},{"time":"4","powerFactor":23},{"time":"5","powerFactor":346},{"time":"6","powerFactor":56},{"time":"7","powerFactor":87},{"time":"8","powerFactor":675},{"time":"9","powerFactor":432},{"time":"10","powerFactor":234},{"time":"11","powerFactor":765}]
const consumptionDay2 = [{
data: consumptionData.map(({time, powerFactor}) => ({x: time, y: powerFactor}))
}]
console.info('consumptionDay2 =', consumptionDay2)
&#13;
这是...将每个consumptionData
条目time
和powerFactor
属性映射到具有x
和y
属性的新对象。
然后,您可以将该数组放入其他对象(如consumptionDay2[0].data
)