Set nested item in object/array from array of keys

前端 未结 3 1747
既然无缘
既然无缘 2021-01-22 03:46

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.

Here is a sample:

3条回答
  •  不思量自难忘°
    2021-01-22 04:33

    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; }

提交回复
热议问题