Ben Carey
Ben Carey

Reputation: 16968

Recursively Convert all Arrays to Objects in Multidimensional Javascript Object

Consider the following object:

const data = {
    foo: 'bar',
    items: [
        {
            id: 1,
            items: [
                {
                    id: 50,
                    content: 'test'
                }
            ]
        },
        {
            id: 2,
            items: [
                {
                    id: 70,
                    content: 'test'
                },
                {
                    id: 85,
                    content: 'test'
                }
            ]
        }
    ]
}

I am currently utilising the Vuex-i18n plugin which only supports string values within arrays, thus I need to iterate through my data and convert all arrays into objects.

I was hoping that I would be able to utilize JSON.parse in some way but I haven't been able to get it to work.

This is what I tried:

const json = '{"foo":"bar","items":[{"id":1,"items":[{"id":50,"content":"test"}]},{"id":2,"items":[{"id":70,"content":"test"},{"id":85,"content":"test"}]}]}';

console.log(JSON.parse(json, (key, value) =>
  typeof value === 'array'
    ? Object.assign({}, value)
    : value
));

Can anyone suggest a way in which this can be achieved? I was hoping that I could avoid recursively iterating over the object but I am not sure if that is possible...

Update

The expected output should look like this:

const data = {
    foo: 'bar',
    items: {
        0: {
            id: 1,
            items: {
                0: {
                    id: 50,
                    content: 'test'
                }
            }
        },
        1: {
            id: 2,
            items: {
                0: {
                    id: 70,
                    content: 'test'
                },
                1: {
                    id: 85,
                    content: 'test'
                }
            }
        }
    }
}

Note all the arrays are now objects...

Upvotes: 3

Views: 54

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could check for array with Array.isArray.

const json = '{"foo":"bar","items":[{"id":1,"items":[{"id":50,"content":"test"}]},{"id":2,"items":[{"id":70,"content":"test"},{"id":85,"content":"test"}]}]}';

console.log(JSON.parse(json, (key, value) => Array.isArray(value)
    ? Object.assign({}, value)
    : value
));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 4

Related Questions