将字符串转换为定界对象键

时间:2018-11-30 18:23:51

标签: javascript arrays loops join delimiter

我正在尝试将字符串转换为定界对象键,但是我需要一些有关如何遍历数组长度并相应地进行连接的帮助。

SET('my.delimited.string.of.unknown.length')

const SET = key => (state, val) => { 
        if(key.indexOf('.') !== -1) {
            let array = key.split(".")
            for (var i = 0; i < array.length; i++) {
                  // what should I do here?
            }
            // desired output based on array length
            // state[ array[0] ][ array[1] ] = val
            // state.my.delimited.string.of.unknown.length = val
        }
}

3 个答案:

答案 0 :(得分:1)

reduce那些非常罕见的用例之一:

  const keys = key.split(".");
  const prop = keys.pop();
  keys.reduce((acc, key) => acc[key], state)[prop] = val;

确保也可以使用for循环来完成此操作:

 let array = key.split("."), acc = state;
 for (var i = 0; i < array.length - 1; i++) {
   acc = acc[ array[i] ];
 }
 acc[ array.pop() ] = val;

答案 1 :(得分:0)

要设置值,可以通过移动给定的对象来分割路径并缩小路径。如果不存在任何对象,请使用名称创建一个新属性。稍后分配值。

function setValue(object, path, value) {
    var keys = path.split('.'),
        last = keys.pop();

    keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}

var test = {};
setValue(test, "first.deep.property", 1);
setValue(test, "and.another.deep.property", 20);
console.log(test);

答案 2 :(得分:0)

您也可以使用一个Array.reduce来完成此操作:

const makeObject = (arr, val, obj={}) => {
  arr.split('.').reduce((r,c,i,a) => r[c] = i == a.length-1 ? val : {}, obj)
  return obj
}

console.log(makeObject("first.deep.property", 1))
console.log(makeObject("and.another.deep.property", 20))