Переберите данные с помощью reduce
, чтобы создать объект, сгруппированный по типу. Вот функция многократного использования - просто введите data
и type
.
const data = [{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Rishi Ranabhat","project":"ABC"},{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Biplap Bhattarai","project":"DEF"},{"billed":"No","designation":"SE","involvement":"Part Time","name":"Ram k","project":"DEF"}];
function getCount(data, type) {
// `map` out the data by type
const typeArr = data.map((obj) => obj[type]);
// Iterate over the type data. We pass in an initial
// object to capture the counts, so we need to use
// `Object.values` to grab the object values at the end
// of the iteration
return Object.values(typeArr.reduce((acc, id) => {
// If the key doesn't exist in the accumulator object
// create it and create a new array at its value
acc[id] = acc[id] || [id, 0];
// Increment the second index (the count)
acc[id][1]++;
// Return the object for the next iteration
return acc;
}, {}));
}
console.log(getCount(data, 'designation'));
console.log(getCount(data, 'project'));
Дополнительная литература
В качестве альтернативы, если вы хотите сделать это за одну операцию и вернуть объект, содержащий сгруппированную информацию, вы можете использовать другой reduce
для перебора основных ключей данных:
const data = [{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Rishi Ranabhat","project":"ABC"},{"billed":"No","designation":"ASE","involvement":"Full Time","name":"Biplap Bhattarai","project":"DEF"},{"billed":"No","designation":"SE","involvement":"Part Time","name":"Ram k","project":"DEF"}];
function getCounts(data) {
// Grab the data keys. It assumes that each object in
// the array has the same keys
const keys = Object.keys(data[0]);
// Using `reduce` iterate over the keys to build
// up an object that groups the results from the inner
// `reduce` operation by key
return keys.reduce((out, key) => {
// `map` out the data by type
const typeArr = data.map((obj) => obj[key]);
// Iterate over the type data. We pass in an initial
// object to capture the counts, so we need to use
// `Object.values` to grab the object values at the end
// of the iteration
out[key] = Object.values(typeArr.reduce((acc, id) => {
// If the key doesn't exist in the accumulator object
// create it and create a new array at its value
acc[id] = acc[id] || [id, 0];
// Increment the second index (the count)
acc[id][1]++;
// Return the object for the next iteration
return acc;
}, {}));
// Return the `out` object for the next iteration
return out;
}, {});
}
console.log(getCounts(data));