javascript - 使用字符串数组将键添加到 json

标签 javascript arrays json

我有一个基本的 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/

相关文章:

JavaScript,通过自定义数据ID查找子DIV

javascript - AngularJS 模块与 CommonJS/ECMA6 模块

Javascript array.push 克隆数组修改原始数组

python - 使用请求和 psycopg2 在 Postgres 中创建/插入 Json

java - 为 MOXy JSON 编码重命名元素名称

javascript - AngularJS Controller 和服务出现问题

javascript - ExtJS : how to make a custom modal window with MessageBox buttons?

c - C中二维数组中的连续圆与Bresenham的圆算法

ruby - 列出日期数组中缺失的月份

json - 无法使用 netty 在 http 客户端中读取响应