Создать многомерный массив [ключ, значение] с уникальным количеством ключей в качестве значения из массива объекта JSON - PullRequest
0 голосов
/ 23 октября 2019

В настоящее время у меня есть массив json-объектов, возвращаемых сервером

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"
  },
   ...more json data
];

Мне нужно создать количество значений в массиве, как показано ниже для представления для диаграмм Google:

[
  //designation count
  ["ASE", 2],
  ["SE", 2]
],
  [
    //project count
    ["ABC", 1],
    ["DEF", 2]
  ],
  //and similarly others.

Какмогу ли я посчитать количество вхождений ключей со значениями предыдущего вхождения нетронутыми, а также в ['key', 'value'] ключа, являющегося уникальным вхождением данных, и значением, являющимся no occurance ???

Ответы [ 3 ]

1 голос
/ 23 октября 2019

Переберите данные с помощью 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));
0 голосов
/ 23 октября 2019

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

const result = data.reduce((acc,cur) => {
  for(let k in cur) {
    if(!acc[k]) {
      acc[k] = [[cur[k], 1]];
    } else {
      const idx = acc[k].findIndex(e => e[0] === cur[k]);
      if(idx !== -1) {
        acc[k][idx][1]++
      } else {
        acc[k].push([cur[k], 1])
      }
    }
  }
  return acc;
}, {});

console.log(result)
0 голосов
/ 23 октября 2019

Много способов сделать это. Вот простой способ (можно почистить, но просто попробовать демо):

Посмотреть на JSFiddle

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

const designations = [],
      projects = [];

for (const record of data) {
  // Count designations
  if (!designations[record.designation]) {
    designations[record.designation] = 0;
  }
  
  designations[record.designation] = designations[record.designation] + 1;

  // Count projects
  if (!projects[record.project]) {
    projects[record.project] = 0;
  }
  projects[record.project] = projects[record.project] + 1;
}

// Merge sets
const final = [designations, projects];

console.log(final);
...