我有一个基本的 json 问题,几个小时以来一直让我头疼,我试图使用字符串数组动态地将键添加到 Json 对象。
这是我的字符串数组:
let key = ['session', 'view_state', 'footer', 'config', 'items']
我还有另一个变量,它是 jsonValue ,它是我的整个 json 对象。我想最终得到以下选项之一:
jsonValue.session.view_state.footer.config.items
jsonValue['session']['view_state']['footer']['config']['items']
这是我使用 forEach
的最佳尝试。
forEach(jsonKeys, (el) => {
jsonCollection += jsonCollection !== undefined ? '."' +[el + '"'] : [ '"' + el + '"' ];
})
但是我得到了这个结果:
undefined"session"."view_state"."footer"."config"."items"
任何帮助将不胜感激!
最佳答案
使用键数组获取值
使用Array#reduce进行迭代,检查当前值的类型,如果是对象,则返回key的值,如果不是则返回undefined
:
const obj = {
"demo": true,
"session": {
"view_state": {
"footer": {
"config": {
"items": [
1,
2
]
}
}
}
}
};
const keys = ['session', 'view_state', 'footer', 'config', 'items'];
const value = keys.reduce((val, key) => val && typeof val === 'object' ?
val[key] : undefind, obj);
console.log(value);
使用keys
数组添加值
使用 Array#reduceRight 创建具有所需值的对象链。使用 Object#assign 用结果更新原始对象:
const keys = ['session', 'view_state', 'footer', 'config', 'items'];
const obj = { demo: true };
Object.assign(obj, keys.reduceRight((val, key) => ({ [key]: val }), [1, 2])); // replace [1, 2] with the actual items
console.log(obj);
关于javascript - 使用字符串数组将键添加到 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47423668/