js根据json数组的某个字段,统计出现的次数,并返回指定的数组

                   var arr = [{
                        name: '98k',
                        xin_hao: '2321',
                        rfid: '135646446'
                    },
                    {
                        name: '98k',
                        xin_hao: '2321',
                        rfid: '135646446'
                    },
                    {
                        name: '982k',
                        xin_hao: '3213',
                        rfid: '135646446'
                    },
                    {
                        name: '983k',
                        xin_hao: '2342121',
                        rfid: '135646446'
                    },
                    {
                        name: '981k',
                        xin_hao: '235521',
                        rfid: '135646446'
                    }
                ]

                   var map = {},
                    dest = [];

                for (var i = 0; i < arr.length; i++) {
                    var field = arr[i];
                    if (!map[field.xin_hao]) {
                        dest.push({
                            xin_hao: field .xin_hao,
                            name: field .name,
                            data: [field]
                        });
                        map[field.xin_hao] = field ;
                    } else {
                        for (var j = 0; j < dest.length; j++) {
                            var fieldd= dest[j];
                            if (fieldd.xin_hao == field.xin_hao) {
                                fieldd.data.push(ai);
                                break;
                            }
                        }
                    }
                }
                console.log(dest)



输出的结果:(次数可以写data.length,比如xin_hao为“2321”的出现了两次)
(4) [{…}, {…}, {…}, {…}]
0:
data: Array(2)
name: "98k"
xin_hao: "2321"
1:
data: Array(1)
name: "982k"
xin_hao: "3213"
2:
data: Array(1)
name: "983k"
xin_hao: "2342121"
3:
data: Array(1)
name: "981k"
xin_hao: "235521"

你可能感兴趣的:(js根据json数组的某个字段,统计出现的次数,并返回指定的数组)