我有一堆带有多个对象,数组,字符串,布尔值,数字等的JSON,这些对象存储在根级别和组件的一个对象中。
这是一个示例:
{ "theme": { "auto": { "sensor": "sensor.sn1_ldr", "below": 600 }, "ui": { "cards": { "round": false, "elevation": 1 } }, ... }, ... }
我设法像这样在数组中传递了项目的路径和新值:
["theme", "auto", "sensor"]
我如何从那里设置该路径的新值?即。等效于:
config.theme.auto.sensor = newValue;
但是使用传递回的路径数组?
我到目前为止的方法:
handleConfigChange = (path, value) => { console.log(path, value); let config = this.state.config; // Set the new value this.setState({ config }); };
您可以存储最后一个键并通过从路径中获取键来减少对象。
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; }