0

In my Vue project, I'm doing an API call to my Laravel (nova) backend, the data is returned as follows.

As you can see the data is an array, which contains an array of objects. Each array represents a record, while each object represents a field in that record.

There is the possibility that a record has unnecessary data.

const data = [
    [
        {
            attribute: 'id',
            value: 1,
            extra: "not needed data"
        },
        {
            attribute: 'title',
            value: 'The Title',
            extra: "not needed data"
        },
    ],
    [
        {
            attribute: 'id',
            value: 2
        },
        {
            attribute: 'title',
            value: 'The Other Title'
        },
    ],
]

I'm wondering how I can use Javascript to flatten this out so it becomes

const data = [
    {id: 1, title: 'The Title'},
    {id: 2, title: 'The Other Title'}
]

What I've tried

I've tried using a combination of map and filter, but the results don't even come close.

Kobe
  • 5,539
  • 1
  • 9
  • 32
Miguel Stevens
  • 6,365
  • 13
  • 52
  • 100

1 Answers1

1

You could use map with reduce, to build an object using only the attribute and value, ignoring all other properties:

const data = [
    [
        {
            attribute: 'id',
            value: 1,
            extra: "not needed data"
        },
        {
            attribute: 'title',
            value: 'The Title',
            extra: "not needed data"
        },
    ],
    [
        {
            attribute: 'id',
            value: 2
        },
        {
            attribute: 'title',
            value: 'The Other Title'
        },
    ],
]

console.log(data.map(a => a.reduce((a, o) => (a[o.attribute] = o.value, a), {})))
Kobe
  • 5,539
  • 1
  • 9
  • 32
  • That's it Kobe! I always wonder how people can think of things like that, I feel like my brain can't understand reduce, or complex maps.. Thanks! – Miguel Stevens Aug 09 '19 at 09:51
  • 2
    @Notflip No worries mate, I've only really just started to get good at using them. If you take time to fully understand how it works, it's a very nice tool to use for data manipulation. If you ever need more help, feel free to ask – Kobe Aug 09 '19 at 09:51