使用JSON数组中的count返回相同的值,Javascript

时间:2018-03-06 17:25:21

标签: javascript arrays json

我的数据似乎是这样的:



const myObj = {
  "incidents": [{
    "id": 4,
    "fullName": "edsadas",
    "address": "Bagbaguin, Pandi, Bulacan",
  }, {
    "id": 5,
    "fullName": "reasdsa",
    "address": "Dalig, Balagtas, Bulacan",
  }, {
    "id": 6,
    "fullName": "dsa",
    "address": "Dalig, Balagtas, Bulacan",
  }],
}




我的问题是,我如何用count返回相似的值,如下所示:

{
  "Dalig, Balagtas, Bulacan": 2,
  "Bagbaguin, Pandi, Bulacan": 1
}

2 个答案:

答案 0 :(得分:5)

您可以使用功能library(ggplot2) library(scales) set.seed(306) data4 <- data.frame(WEEK.NUMBER = as.vector(outer(2016:2017, 40:52, function(x,y) paste(x, y, sep="-"))), variable = c(rep("CURRENT.WEEK.DEATHS", 26), rep("PREVIOUS.WEEK.DEATHS", 26)), value = sample(0:5, 52, replace = TRUE), stringsAsFactors = FALSE) # NEW DATE VARIABLE data4$week_date <- as.Date(paste(data4$WEEK.NUMBER, 1, sep="-"), format="%Y-%W-%w") ggplot(data4, aes(fill=variable, y=value, x=week_date), color="black") + geom_bar( stat="identity") + labs(x = "Week of Death", y="Number of Deaths") + scale_fill_manual(name = '', guide = 'legend', labels = c('Death Reported Previous Week', 'Death Reported Current Week'), values = c( "#00ffff","#009933")) + scale_x_date(breaks = date_breaks("1 weeks"), labels = date_format("%Y-%W"))+ theme(legend.position='bottom') + theme( axis.text.x = element_text(angle = 90, hjust = 1, size =5))

reduce
var obj = {  "incidents": [{      "id": 4,      "fullName": "edsadas",      "address": "Bagbaguin, Pandi, Bulacan",    },    {      "id": 5,      "fullName": "reasdsa",      "address": "Dalig, Balagtas, Bulacan",    },    {      "id": 6,      "fullName": "dsa",      "address": "Dalig, Balagtas, Bulacan",    }  ]};
var result = obj.incidents.reduce((a, c) => {
            a[c.address] = (a[c.address] || 0) + 1
            return a;
         }, {});

console.log(result);

使用.as-console-wrapper { max-height: 100% !important; top: 0; }reduce

comma operator
var obj = {  "incidents": [{      "id": 4,      "fullName": "edsadas",      "address": "Bagbaguin, Pandi, Bulacan",    },    {      "id": 5,      "fullName": "reasdsa",      "address": "Dalig, Balagtas, Bulacan",    },    {      "id": 6,      "fullName": "dsa",      "address": "Dalig, Balagtas, Bulacan",    }  ]},         
    result = obj.incidents
                .reduce((a, c) => (a[c.address] = (a[c.address] || 0) + 1, a), {});

console.log(result);

答案 1 :(得分:1)

您可以迭代它们并每次递增值。如果找不到,只需指定B=tk.Button(self.root,text="quit",command=lambda:sys.exit()) B.grid()

1