Miguel Stevens
Miguel Stevens

Reputation: 9191

Flatten data from an object with an array of objects

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.

Upvotes: 0

Views: 307

Answers (1)

Kobe
Kobe

Reputation: 6446

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), {})))

Upvotes: 1

Related Questions