Javascript:如何从点分隔字符串创建对象?

sro*_*ley 1 javascript object

编辑:修改短语,因为这不是一个功课问题.那些低估这一点的人应该感到羞耻.;)

我遇到了这个潜在的情景,我向我的一些员工提出了一个测试问题.我可以想到几种方法来解决这个问题,但它们都不是很漂亮.我想知道哪种解决方案最适合这个以及任何优化提示.这是问题:

给定点符号中的任意字符串"mystr"(例如mystr ="node1.node2.node3.node4")任意长度,写一个名为"expand"的函数,它将创建这些项中的每一个作为js中的新节点层宾语.对于上面的示例,它应该输出以下内容,因为我的对象名称是"blah":

blah: { node1: { node2: { node3: { node4: {}}}}}
Run Code Online (Sandbox Code Playgroud)

从函数调用:

mystr = "node1.node2.node3.node4";
blah = {};
expand(blah,mystr);
Run Code Online (Sandbox Code Playgroud)

或者,如果更容易,可以创建函数以将变量设置为返回值:

mystr = "node1.node2.node3.node4";
blah = expand(mystr);
Run Code Online (Sandbox Code Playgroud)

额外信用:有一个可选的函数参数,用于设置最后一个节点的值.所以,如果我调用我的函数"expand"并像这样调用它:expand(blah,mystr,"value"),输出应该与之前一样,但是node4 ="value"而不是{}.

Dzm*_*hko 9

ES6你可以这样做:

function expand(str, val = {}) {
  return str.split('.').reduceRight((acc, currentValue) => {
    return { [currentValue]: acc }
  }, val)
}

const blah = expand('a.b.c.d', 'last value')
Run Code Online (Sandbox Code Playgroud)


Osc*_*car 8

这是一种突然出现在我脑海中的方法.它在点符号上拆分字符串,然后循环遍历节点以使用"移位引用"创建对象内部的对象(不确定这是否是正确的术语).

该对象output在函数中包含整个功能正在构建的完整的对象,但ref会保留转移到越陷越深内引用output,作为新的子对象在for循环创建.

最后,最后一个值应用于最后给定的名称.

function expand(str, value)
{
    var items = mystr.split(".") // split on dot notation
    var output = {} // prepare an empty object, to fill later
    var ref = output // keep a reference of the new object

    //  loop through all nodes, except the last one
    for(var i = 0; i < items.length - 1; i ++)
    {
        ref[items[i]] = {} // create a new element inside the reference
        ref = ref[items[i]] // shift the reference to the newly created object
    }

    ref[items[items.length - 1]] = value // apply the final value

    return output // return the full object
}
Run Code Online (Sandbox Code Playgroud)

然后返回该对象,因此可以使用此表示法:

mystr = "node1.node2.node3.node4";
blah = expand(mystr, "lastvalue");
Run Code Online (Sandbox Code Playgroud)

  • @Oscar为什么缺少分号? (3认同)