Q:

Return multiple elements using Lodash _.get?

I have this JavaScript object:
const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
}

I was able to select only one item using Lodash's _.get method.
_.get(object, 'categories[0].items[0].image')
// => "path/to/file-1.png"

But I need an array with all occurrences, not just from position 0. Something like this:
_.get(object, 'categories[].items[].image')
// => ["path/to/file-1.png", "path/to/file-2.png", "path/to/file-3.png", "path/to/file-4.png", "path/to/file-5.png", "path/to/file-6.png"]

Is it possible to do it using Lodash?
If it's not possible, do you have any idea how to implement it?
EDIT: I'm looking for something like _.get from Lodash, where I can supply the "search schema" (path) as string. Obviously I know how to solve this with map, reduce, etc.

A:

This is my implementation of a flatGet function that can handle arrays:

const flatGet = (object, path) => {
  const p = path.match(/[^.\[\]]+/g)
    
  const getItem = (item, [current, ...path]) => {  
    if(current === undefined) return item
    
    if(typeof item !== 'object') return undefined
    
    if(Array.isArray(item)) return item.flatMap(o => getItem(o[current], path))
    
    return getItem(item[current], path)
  }
    
  return getItem(object, p)
}

const object = {"categories":[{"title":"Category 1","items":[{"title":"Item 1","image":"path/to/file-1.png"},{"title":"Item 2","image":"path/to/file-2.png"},{"title":"Item 3","image":"path/to/file-3.png"}]},{"title":"Category 2","items":[{"title":"Item 4","image":"path/to/file-4.png"},{"title":"Item 5","image":"path/to/file-5.png"},{"title":"Item 6","image":"path/to/file-6.png"}]}]}

var result = flatGet(object, 'categories.items.image')

console.log(result)

