TO Get The Number Of Count From JSON In Javascript?
Solution 1:
Well, first of all that is not valid JSON. You need array delimiters around it, commas between items, and delimiters around all identifiers and all strings.
The code that you have doesn't return what you described. It returns this:
{ cardName: "ARR", portCount: 9 }
Your first loop seems to be intended to get the distinct card names, but it doesn't. It just makes another array with the card names in the same order as in the input array. The second loop looks for the card names in the input array, but as you have duplicates in the countOfPort
array the items will be matched multiple times. That's why you are getting a port count of 9 while there are only five ports in the data.
Just loop through the array once, and use the card name as identifier in the map. If the name already exists in the map then add to it, otherwise add a new item in the map:
var json = '[{"cardAid":"ALPHG","displayName":"ALPHG","port":"A"},{"cardAid":"ALPHG","displayName":"ALPHG","port":"B"},{"cardAid":"SFD","displayName":"SFD","port":"C"},{"cardAid":"SFD","displayName":"SFD","port":"D"},{"cardAid":"ARR","displayName":"ARR","port":"E"}]';
var arr = JSON.parse(json);
console.log(count(arr));
function count(arr) {
var map = {};
for (var i = 0; i < arr.length; i++) {
var name = arr[i].cardAid;
var port = arr[i].port;
if (name in map){
map[name].Count++;
map[name].Port += ',' + port;
} else {
map[name] = { Count: 1, Port: port };
}
}
return map;
}
The function will return an object:
{
ALPHG: { Count: 2, Port: "A,B" },
ARR: { Count: 1, Port: "E" },
SFD: { Count: 2, Port: "C,D" }
}
Solution 2:
format your JSON properly, so that it is easier for readers to work with.
This kind of problem is best tackled with underscore library http://underscorejs.org/
This is your data:
var data = [
{
cardAid: "ALPHG",
displayName: "ALPHG",
port: "A"
},
{
cardAid: "ALPHG",
displayName: "ALPHG",
port: "B"
},
{
cardAid: "SFD",
displayName: "SFD",
port: "C"
},
{
cardAid: "SFD",
displayName: "SFD",
port: "D"
},
{
cardAid: "ARR",
displayName: "ARR",
port: "E"
}
];
This is the code your need:
var result = _.map(_.groupBy(data, "cardAid"), function(group, cardAid) {
return {
cardAid: cardAid,
count: _.size(group),
port: _.pluck(group, "port")
};
});
This is the result you get:
// result:
// [
// {
// "cardAid": "ALPHG",
// "count": 2,
// "port": ["A", "B"]
// },
// {
// "cardAid": "SFD",
// "count": 2,
// "port": ["C", "D"]
// },
// {
// "cardAid": "ARR",
// "count": 1,
// "port": ["E"]
// }
// ]
Post a Comment for "TO Get The Number Of Count From JSON In Javascript?"