将所有数组递归转换为多维Javascript对象中的对象

Ben*_*rey 3 javascript arrays json

考虑以下对象:

const data = {
    foo: 'bar',
    items: [
        {
            id: 1,
            items: [
                {
                    id: 50,
                    content: 'test'
                }
            ]
        },
        {
            id: 2,
            items: [
                {
                    id: 70,
                    content: 'test'
                },
                {
                    id: 85,
                    content: 'test'
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我目前正在使用Vuex-i18n插件,该插件仅支持数组中的字符串值,因此我需要遍历数据并将所有数组转换为对象。

我希望我能够以JSON.parse某种方式利用它,但我一直无法使它发挥作用。

这是我尝试的:

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
));
Run Code Online (Sandbox Code Playgroud)

谁能建议实现这一目标的方法?我希望我可以避免递归地迭代该对象,但是我不确定是否可行...

更新资料

预期的输出应如下所示:

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'
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意所有的数组现在都是对象...

Nin*_*olz 5

您可以使用检查数组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
));
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)