考虑以下对象:
我目前正在使用Vuex-i18n插件,该插件仅支持数组中的字符串值,因此我需要遍历我的数据并将所有数组转换为对象。
我希望我能以某种方式利用
这是我尝试过的:
注意,现在所有的数组都是对象...
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'
}
}
}
}
}
注意,现在所有的数组都是对象...