从键数组中设置对象/数组中的嵌套项 [英] Set nested item in object/array from array of keys

查看:60
本文介绍了从键数组中设置对象/数组中的嵌套项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆JSON,其中包含多个对象,数组,字符串,布尔值,数字等,这些对象存储在根级别和组件的一个对象中.

I have a bunch of JSON with multiple objects, arrays, strings, booleans, numbers etc. which are stored in one object at the root level and component.

以下是示例:

{
  "theme": {
    "auto": {
      "sensor": "sensor.sn1_ldr",
      "below": 600
    },
    "ui": {
      "cards": {
        "round": false,
        "elevation": 1
      }
    },
    ...
  },
  ...
}

我设法像这样在数组中传递了项目的路径和新值:

I have managed to pass back the path and new value of the item in an array like so:

["theme", "auto", "sensor"]

如何从那里设置该路径的新值? IE.等效于:

How do I from there set the new value of that path? ie. the equivalent of:

config.theme.auto.sensor = newValue;

但是使用传递回的路径数组吗?

but using the path array passed back?

我到目前为止的方法:

handleConfigChange = (path, value) => {
  console.log(path, value);
  let config = this.state.config;
  // Set the new value

  this.setState({ config });
};

推荐答案

您可以存储最后一个键并通过从路径中获取键来减少对象.

You could store the last key and reduce the object by taking the keys from the path.

function setValue(object, path, value) {
    var last = path.pop();
    path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}

var config = { theme: { auto: { sensor: "sensor.sn1_ldr", below: 600 }, ui: { cards: { round: false, elevation: 1 } } } },
    path = ["theme", "auto", "sensor"];

setValue(config, path, 'foo');

console.log(config);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于从键数组中设置对象/数组中的嵌套项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆