gpt4 book ai didi

javascript - 无法在 json 数组对象迭代中获得所需或类似的输出?

转载 作者:行者123 更新时间:2023-12-03 03:24:33 24 4
gpt4 key购买 nike

我有以下 json 对象,我想获得如下所示的所需输出。

var testdata = [{
"x": [
"Jan-10",
"Feb-10",
"Mar-10",
"Apr-10",
"May-10"
],
"y": [
"100.0",
"25.0",
"100.0",
"60.0",
"500.0"
],
"xf": "Jan-10",
"xl": "May-10",
"yf": "100.0",
"yl": "500.0",
"xtitle": "day",
"ytitle": "rs"
},
{
"x": [
"Jan-11",
"Feb-11",
"Mar-11",
"Apr-11",
"May-11"
],
"y": [
"450.0",
"650.0",
"300.0",
"70.0",
"360.0"
],
"xf": "Jan-11",
"xl": "May-11",
"yf": "450.0",
"yl": "360.0",
"xtitle": "day",
"ytitle": "rs"
}
];

我想迭代这个,应该得到类似的输出(y1和y2只是它们的值,这些键可以是任何东西):

[{
"day": "Jan",
"y1": "100",
"y2": "450"
},
{
"day": "Feb",
"y1": "25",
"y2": "650"
},
{
"day": "Mar",
"y1": "100",
"y2": "300"
},
{
"day": "Apr",
"y1": "60",
"y2": "70"
},
{
"day": "May",
"y1": "500",
"y2": "360"
}
]

我尝试过:

if(testdata.length > 0){
var outarr = [];
for(var i = 0; i < testdata[0].x.length; i++) {
outarr.push(
{
"x": testdata[0].x[i],
"y": testdata[0].y[i]
})
}
console.log(JSON.stringify(outarr));
}

但我没有从上面的循环中获得实际输出,请让我知道如何执行此操作以获得类似的输出。创建Fiddle 。提前致谢!

最佳答案

假设testdata的结构是一致的。

var testdata = [{
"x": [
"Jan-10",
"Feb-10",
"Mar-10",
"Apr-10",
"May-10"
],
"y": [
"100.0",
"25.0",
"100.0",
"60.0",
"500.0"
],
"xf": "Jan-10",
"xl": "May-10",
"yf": "100.0",
"yl": "500.0",
"xtitle": "day",
"ytitle": "rs"
},
{
"x": [
"Jan-11",
"Feb-11",
"Mar-11",
"Apr-11",
"May-11"
],
"y": [
"450.0",
"650.0",
"300.0",
"70.0",
"360.0"
],
"xf": "Jan-11",
"xl": "May-11",
"yf": "450.0",
"yl": "360.0",
"xtitle": "day",
"ytitle": "rs"
}
];

if(testdata){
months = testdata[0]['x'];


output = [];
for(var i = 0; i < months.length; i++){
month = months[i].split('-')[0]
output.push({
"month" : month,
"y1" : testdata[0]['y'][i],
"y2" : testdata[1]['y'][i]
});
}

console.log(output)
}

如果您有两个以上的条目,您当然可以考虑这一点:

if(testdata){
months = testdata[0]['x'];
numentries = testdata.length;

output = [];
for(var i = 0; i < months.length; i++){
month = months[i].split('-')[0]

monthData = {
"month" : month
}

for(var x = 0; x < numentries; x++){
monthData['y'+x] = testdata[x]['y'][i]
}

output.push(monthData);
}

console.log(output)
}

关于javascript - 无法在 json 数组对象迭代中获得所需或类似的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46389791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com