简体   繁体   English

在JSON数组Javascript中返回与count相同的值

[英]Return the same values with count in a JSON Array, Javascript

My data seems to be like this: 我的数据似乎是这样的:

 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", }], } 

My question, how can i return the similar values with count, like this: 我的问题是,如何返回带有count的相似值,如下所示:

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

You can use the function reduce : 您可以使用函数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; } 

Using reduce and comma operator : 使用reducecomma 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); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can iterate over them and increment the value every time. 您可以遍历它们,并每次都增加值。 If not found just assign 1 如果找不到,则分配1

 const data = [ { "id": 4, "fullName": "edsadas", "address": "Bagbaguin, Pandi, Bulacan", }, { "id": 5, "fullName": "reasdsa", "address": "Dalig, Balagtas, Bulacan", }, { "id": 6, "fullName": "dsa", "address": "Dalig, Balagtas, Bulacan", }]; const count = data.reduce((acc, item) => (acc[item.address] = acc[item.address] ? acc[item.address] + 1 : 1, acc), {}); console.log(count); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM