创建一个带有大小参数的 JSON Sing JavaScript



我正在编写一个代码,它将从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 格式不正确,请告诉我该怎么做。

谢谢

您正在使用数组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);

您应该使用括号表示法定义对象并设置属性以填充属性

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);

您可以使用

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));

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));

最新更新