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

3
考虑以下对象:
const data = {
    foo: 'bar',
    items: [
        {
            id: 1,
            items: [
                {
                    id: 50,
                    content: 'test'
                }
            ]
        },
        {
            id: 2,
            items: [
                {
                    id: 70,
                    content: 'test'
                },
                {
                    id: 85,
                    content: 'test'
                }
            ]
        }
    ]
}

我目前正在使用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
));

有人能提供一种实现这个的方法吗?我希望能避免对对象进行递归迭代,但我不确定是否可能...

更新

期望的输出应该是这样的:

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'
                }
            }
        }
    }
}

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

你能否提供一个期望输出的示例? - Alexander Nied
你期望的输出是什么? - kemicofa ghost
1
不行,你不能在没有键的情况下嵌套对象。 - Nina Scholz
@VLAZ - 指出得好,我快速完成了它,因为我想为您更新它,但应该很清楚我需要什么。我相信Nina已经完美解决了这个问题。 - Ben Carey
@BenCarey,这一点根本不清楚。我已经猜测了类似数组的东西(并且猜对了),但是我也有可能猜错。你的例子进一步混淆了问题,因为它是无效的。如果这很明显,你在发布问题后就不会立即得到三个关于你实际想要的问题。 - VLAZ
显示剩余4条评论
1个回答

4

你可以使用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; }


这似乎正是我在寻找的!非常感谢! - Ben Carey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接