如何将以下数据转换为组数据?

时间:2020-06-06 14:15:05

标签: javascript arrays json typescript

这是我的输入:

  data = [
    { name: "John Cena", groupName: "WWE" },
    { name: "Nandini", groupName: null },
    { name: "Rock", groupName: "WWE" },
    { name: "Vinay", groupName: null },
    { name: "Rey Mesterio", groupName: "WWE" },
    { name: "Gokul", groupName: "FSD" },
    { name: "Rohitha", groupName: "FSD" }
  ];

我需要以以下格式输出:

  requiredFormat = [
    { name: "FSD", value: ["Gokul", "Rohitha"] },
    { name: "WWE", value: ["John Cena", "Rock", "Rey Mesterio"] },
    { name: null, value: ["Nandini", "Vinay"] }
  ];

3 个答案:

答案 0 :(得分:0)

您可以简单地reduce并使用Object.values()

var data = [ { name: "John Cena", groupName: "WWE" }, { name: "Nandini", groupName: null }, { name: "Rock", groupName: "WWE" }, { name: "Vinay", groupName: null }, { name: "Rey Mesterio", groupName: "WWE" }, { name: "Gokul", groupName: "FSD" }, { name: "Rohitha", groupName: "FSD" } ];

var result = Object.values(data.reduce((acc, {name, groupName})=>{
    acc[groupName] =acc[groupName] || {name:groupName, value:[]};
    acc[groupName].value.push(name);
    return acc;
},{}));

console.log(result);

答案 1 :(得分:0)

您可以使用reduce并检查数组值是否已经存在。如果是这样,添加到它。如果没有,请创建它。

const data = [
  { name: "John Cena", groupName: "WWE" },
  { name: "Nandini", groupName: null },
  { name: "Rock", groupName: "WWE" },
  { name: "Vinay", groupName: null },
  { name: "Rey Mesterio", groupName: "WWE" },
  { name: "Gokul", groupName: "FSD" },
  { name: "Rohitha", groupName: "FSD" }
];

const requiredFormat = data.reduce((acc, el) => {
  const found = acc.find(({ name }) => name === el.groupName);
  if (found) found.value.push(el.name);
  else acc.push({ name: el.groupName, value: [el.name] })
  return acc;
}, []);

console.log(requiredFormat);

答案 2 :(得分:0)

使用Array.reduce解决您的问题

const data = [
    { name: "John Cena", groupName: "WWE" },
    { name: "Nandini", groupName: null },
    { name: "Rock", groupName: "WWE" },
    { name: "Vinay", groupName: null },
    { name: "Rey Mesterio", groupName: "WWE" },
    { name: "Gokul", groupName: "FSD" },
    { name: "Rohitha", groupName: "FSD" }
  ];

const requiredFormat = data.reduce((acc, item, key) => {
    const group = acc.find(group => group.name === item.groupName);
    if (!group) {
        acc.push({name: item.groupName, value: [item.name]})
    } else {
        group.value.push(item.name);
    }
    return acc;
}, []);

console.log(requiredFormat);