我有一个与此相似的json
{
"id": "1",
"month": "January",
"type": "inc",
"Value": "780.00",
"year": "2018",
},
{
"id": "2",
"month": "January",
"type": "inc",
"Value": "80.00",
"year": "2018",
},
{
"id": "3",
"month": "February",
"type": "inc",
"Value": "100.00",
"year": "2018",
},...
现在我需要从对象中获得所有月份的所有Value
,因为您可以看到我可能有更多具有相同月份名称的对象。我越来越近地创建了两个带有月列表的数组1和带有值的数组1,但是我被困住了,有人可以引导我找到正确的路径吗?
理想的输出将是得到一个像["January"=>1500, "February"=>2000...]
这样的数组,或者有2个数组,其中1个是有收入的月份列表(我已经有了),第二个是这些月份的总收入,就像这样:["January", "February", "March"..]
和第二个[1500, 2000, 300...]
答案 0 :(得分:5)
您可以使用函数Array.prototype.reduce
来按月对每个Value
求和。
let arr = [{ "id": "1", "month": "January", "type": "inc", "Value": "780.00", "year": "2018", }, { "id": "2", "month": "January", "type": "inc", "Value": "80.00", "year": "2018", }, { "id": "3", "month": "February", "type": "inc", "Value": "100.00", "year": "2018", }],
result = arr.reduce((a, {month, Value}) => {
a[month] = (a[month] || 0) + +Value;
return a;
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您可以
var fabuaryDate = yourdata
.filter(function(data) { return data.month == "February" })
.map(function(x){return {value: x.Value} })
答案 2 :(得分:1)
实际上我几乎无法理解您想要实现的目标。请提供一些示例。 如果我对您的理解正确,则可以使用js数组的map函数将每个对象映射到其Value。
let arr = [...];
console.log(arr.map(item => item.Value));
答案 3 :(得分:1)
要获得以下格式的结果:
{
jan : [1,2,3],
feb : [3,4,5,6],
april : [3,4,5]
}
执行此操作:
var output = {}
arr.forEach(element => {
if(!output[element.month]){
output[month] = new Array();
}
output[month].push(element.value);
});
答案 4 :(得分:1)
您可以迭代对象,并用要提取的字段的值填充数组,如下所示:
const data = [ {
"id": "1",
"month": "January",
"type": "inc",
"Value": 780.00,
"year": "2018",
},
{
"id": "2",
"month": "January",
"type": "inc",
"Value": 80.00,
"year": "2018",
},
{
"id": "3",
"month": "February",
"type": "inc",
"Value": 100.00,
"year": "2018",
}];
let dataArray = data.reduce((accum, d) => {
if(!accum[d.month]) accum[d.month] = 0;
accum[d.month] += d.Value;
return accum;
},{});
console.log(dataArray);
答案 5 :(得分:1)
尽管您似乎对此处尝试的内容还不够清楚,但这是一个示例,可以用来读取json中的所有值。
function myFunction(item) {
console.log(item.month + " with the value " + item.Value)
}
var jsonArray = [{"id": "1","month": "January", "type": "inc", "Value": "780.00", "year": "2018" }, { "id": "2", "month": "January", "type": "inc", "Value": "80.00", "year": "2018" }, { "id": "3", "month": "February", "type": "inc", "Value": "100.00", "year": "2018" }];
jsonArray.forEach(myFunction);
由于要使用对象数组,因此必须访问该数组中的每个对象,然后获取所需的属性。
希望这项帮助,祝您生活愉快。