如何使用对象对多个元素进行分组?

时间:2019-05-29 10:53:44

标签: javascript jquery arrays object

我的数组在下面给出

data = [{
  status: 1,
  file_name: "file1",
  table_name: "emp2",
  table_details: [Array(5)],
  {
    status: 1,
    file_name: "file2",
    table_name: "sheet1",
    table_details: [Array(11)],
    {
      status: 1,
      file_name: "file1",
      table_name: "emp1",
      table_details: [Array(11)],
      {
        status: 1,
        file_name: "file2",
        table_name: "sheet1",
        table_details: [Array(11)],
]

我想得到这个预期的结果

{
  file2: {
    table_name: ["sheet1"],
    table_details: [Array(11)]
  },
  file1: {
    table_name: (2)["emp1", "emp2"],
    table_details: (2)[Array(5), Array(11)]
  }

2 个答案:

答案 0 :(得分:1)

您可以使用reduce:

var data = [{
  status: 1,
  file_name: "file1",
  table_name: "emp2",
  table_details: [Array(5)],
}, {
  status: 1,
  file_name: "file2",
  table_name: "sheet1",
  table_details: [Array(11)],
}, {
  status: 1,
  file_name: "file1",
  table_name: "emp1",
  table_details: [Array(11)],
}, {
  status: 1,
  file_name: "file2",
  table_name: "sheet1",
  table_details: [Array(11)],
}]

const obj = data.reduce((acc, {
  file_name,
  table_name,
  table_details
}) => {
  if (acc[file_name]) {
    if (!acc[file_name].table_name.includes(table_name)) acc[file_name].table_name.push(table_name)
    acc[file_name].table_details.push(table_details)
  } else {
    acc[file_name] = {
      table_name: [table_name],
      table_details: [table_details]
    }
  }
  return acc
}, {})

console.log(obj)

答案 1 :(得分:0)

像这样使用reduce

const data = [{status:1,file_name:"file1",table_name:"emp2",table_details:[Array(5)]},{status:1,file_name:"file2",table_name:"sheet1",table_details:[Array(11)]},{status:1,file_name:"file1",table_name:"emp1",table_details:[Array(11)]},{status:1,file_name:"file2",table_name:"sheet1",table_details:[Array(11)]}];
const res = data.reduce((acc, { file_name, table_name, table_details }) => {
  acc[file_name] = acc[file_name] || { table_name: [], table_details: [] };
  acc[file_name].table_name.push(table_name);
  acc[file_name].table_details.push(table_details);
  acc[file_name].table_name = [...new Set(acc[file_name].table_name)];
  acc[file_name].table_details = [...new Set(acc[file_name].table_details)];
  return acc;
}, {});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

undefined的大量数量是Array构造的结果。)