我编写的代码将返回来自dynamodb的结果,并且应该将此结果转换为json,我能够执行此操作,但需要更多数据。
这是我的代码。
var item = [
{ "max": "0.575", "ingredients": "a" },
{ "max": "10.25", "ingredients": "b" },
{ "max": "98.5", "ingredients": "c" }
];
var valuesForChart = {
data: []
};
item.forEach(function(subItem) {
var names = subItem.ingredients;
var level = subItem.max;
valuesForChart.data.push({
[names]: level
});
});
console.log(valuesForChart);

我当前的输出显示如下。
{
"data": [
{
"a": "0.575"
},
{
"b": "10.25"
},
{
"c": "98.5"
}
]
}
但我希望它为
{
"data": {
"a": "0.575",
"b": "10.25",
"c": "98.5"
},
"max":"98.5"
}
道歉,如果JSON格式不正确,请告诉我如何才能这样做。
由于
答案 0 :(得分:1)
您正在使用数组data
,因为您需要一个对象。更改data
声明,不要使用push
。
然后,计算最大值并将其放入valuesForChart
var item = [
{ "max": "0.575", "ingredients": "a" },
{ "max": "10.25", "ingredients": "b" },
{ "max": "98.5", "ingredients": "c" }
];
var valuesForChart = {
data: {}
};
var max=undefined;
item.forEach(function(subItem) {
var names = subItem.ingredients;
var level = subItem.max;
valuesForChart.data[names] = level
if(max === undefined || max < level){
max = level;
}
});
valuesForChart.max=max;
console.log(valuesForChart);
答案 1 :(得分:0)
您应该使用括号表示法定义对象和设置属性以填充属性
var item = [{
"max": "0.575",
"ingredients": "a"
},
{
"max": "10.25",
"ingredients": "b"
},
{
"max": "98.5",
"ingredients": "c"
}
];
var valuesForChart = {
data: {}, //Define as object
max: 0
};
item.forEach(function(subItem) {
var names = subItem.ingredients;
var level = subItem.max;
valuesForChart.data[names] = level; //Use Bracket notion to populate
//Calculate max
if (valuesForChart.max < parseFloat(level))
valuesForChart.max = level;
});
console.log(valuesForChart);
答案 2 :(得分:0)
您可以使用Array.prototype.reduce
轻松完成此操作。
var item = [{
"max": "0.575",
"ingredients": "a"
},
{
"max": "10.25",
"ingredients": "b"
},
{
"max": "98.5",
"ingredients": "c"
}
];
let res = {};
res.data = item.reduce((acc, {
ingredients,
max
}) => {
acc[ingredients] = max;
return acc;
}, {});
res.max = Math.max(...item.map(({max})=>Number(max)))+"";
console.log(JSON.stringify(res, null, 4));
答案 3 :(得分:0)
Sometnihg是这样的?
var item = [
{ "max": "0.575", "ingredients": "a" },
{ "max": "10.25", "ingredients": "b" },
{ "max": "98.5", "ingredients": "c" }
];
var valuesForChart = {
"data":{}
};
item.forEach(function(subItem) {
valuesForChart.data[subItem.ingredients] = subItem.max;
var max = valuesForChart.max;
if(max === undefined || max < subItem.max){
valuesForChart.max = subItem.max;
}
});
alert(JSON.stringify(valuesForChart));