Javascript根据另一个值获取json中的值
我有一个类似于这个的jsonJavascript根据另一个值获取json中的值,javascript,json,Javascript,Json,我有一个类似于这个的json { "id": "1", "month": "January", "type": "inc", "Value": "780.00", "year": "2018", }, { "id": "2", "month": "January", "type": "inc", "Value": "80.00", "year": "2018", }, {
{
"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",
},...
现在我需要从对象中获取所有月份的所有值
,您可以看到,我可能有更多具有相同月份名称的对象。我越接近于创建2个数组,1个是月列表,1个是值,但我被卡住了,有人能引导我找到正确的路径吗
理想的输出是得到一个像这样的数组,[“一月”=>1500,“二月”=>2000…]
或者有两个数组,一个是有收入的月份列表(我已经有了),第二个是这些月份的总收入,所以它是这样的:[“一月”、“二月”、“三月”]
和第二个[15002000300…]
您可以
var fabuaryDate = yourdata
.filter(function(data) { return data.month == "February" })
.map(function(x){return {value: x.Value} })
您可以使用该函数按月对每个值进行求和
let arr=[{“id”:“1”,“月”:“1”,“类型”:“inc”,“值”:“780.00”,“年”:“2018”},{“id”:“2”,“月”:“1”,“类型”:“inc”,“值”:“80.00”,“年”:“2018”,},{“id”:“3”,“月”:“2”,“类型”:“inc”,“值”:“100.00”,“年”:“2018”,
结果=arr.reduce((a,{month,Value})=>{
a[月]=(a[月]| 0)+值;
返回a;
},Object.create(null));
console.log(结果);
。作为控制台包装{max height:100%!important;top:0;}
我实际上几乎无法理解您想要实现什么。请提供一些示例。
如果我理解正确,您可以使用js数组的map函数将每个对象映射到它的值
let arr = [...];
console.log(arr.map(item => item.Value));
要以以下格式获取结果:
{
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);
});
您可以迭代对象并用要提取的字段值填充数组,如下所示:
const data=[{
“id”:“1”,
“月”:“一月”,
“类型”:“公司”,
“价值”:780.00,
“年份”:“2018年”,
},
{
“id”:“2”,
“月”:“一月”,
“类型”:“公司”,
“价值”:80.00,
“年份”:“2018年”,
},
{
“id”:“3”,
“月”:“二月”,
“类型”:“公司”,
“价值”:100.00,
“年份”:“2018年”,
}];
让dataArray=data.reduce((acum,d)=>{
如果(!累计[d.month])累计[d.month]=0;
累计月数+=d.值;
返回累计;
},{});
console.log(dataArray);
尽管您似乎对此处尝试的内容还不够清楚,但这是一个示例,说明了您可以如何读取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);
由于使用的是对象数组,因此必须访问数组中的每个对象,然后获取所需的属性
希望这有帮助,祝你度过愉快的一天。发布所需的输出和你迄今为止所做的尝试。是的,但这只会在2月份得到,我需要它在所有月份将其放入图表中,这很好,但我需要一个月的总值作为总和,所以1月份就是860@Radu033不可能循环这些值并将它们相加吗哦,非常简单,非常感谢,到目前为止我已经有超过25行代码了。对不起,我在问题中解释得更好