0

I have the following object structure:

[{
  directory: 'dir1',
  fileName: 'file1.png'
  },
{
  directory: 'dir2',
  fileName: 'file2.png'
  },
{
  directory: 'dir1',
  fileName: 'file2.png'
  },
{
  directory: 'dir1',
  fileName: 'file3.png'
  },
{
  directory: 'dir2',
  fileName: 'test.png'
  }
}]

I want to postprocess this information to yield the following grouping:

{
  "dir1": ["file1.png", "file2.png"],
  "dir2": ["file1.png", "file2.png"],
}

I'm using just plain old vanilla JS. What is the best way to accomplish something like this?

John Lippson
  • 1,269
  • 5
  • 17
  • 36
  • 2
    it would be best if you made an attempt to solve this problem, then come back here if you need help, rather than asking us outright to solve the problem for you. – jdigital Sep 03 '18 at 00:37
  • 1
    or you could, you know, use the search bar at the top of this site – Greg Sep 03 '18 at 00:38

1 Answers1

1

const data = [{
    directory: 'dir1',
    fileName: 'file1.png'
  },
  {
    directory: 'dir2',
    fileName: 'file2.png'
  },
  {
    directory: 'dir1',
    fileName: 'file2.png'
  },
  {
    directory: 'dir1',
    fileName: 'file3.png'
  },
  {
    directory: 'dir2',
    fileName: 'test.png'
  }
];

const result = data.reduce((acc, {
  directory,
  fileName
}) => {
  acc[directory] ? acc[directory].push(fileName) : (acc[directory] = [fileName]);
  return acc;
}, {})

console.log(result)
marzelin
  • 10,790
  • 2
  • 30
  • 49
  • Code–only answers aren't particularly helpful, especially when the OP doesn't seem to have any idea of how to go about the task. – RobG Sep 03 '18 at 00:51
  • @RobG I agree, but this is a generic question that already has an answer (probably many). I've just couldn't resist to solve this ;) – marzelin Sep 03 '18 at 00:57
  • Unfortunately the person who asks the question is nearly always poorly qualified to determine the suitability of answers. The first answer in the marked duplicate has a simpler, more compatible answer (though still no explanation). The idea is to have the OP go to the duplicate, see the many answers (30 in this case) and maybe learn something. If maintainability is a criterion, I'd prefer simple if..else blocks. Marginally more code, but likely more performant and easily read. :-) – RobG Sep 03 '18 at 03:23