在try 更自如地使用递归函数的同时,我try 编写一个函数,该函数接受一个以点分隔的字符串,并将其转换为一个对象.

{
  user: {
    first: {
      name: 'robert'
    }
  }
}

以下是我的try :

function objectifyHelper(array, object) {
    if (array.length === 2) {
        const [key, value] = array;
        object[key] = value;
        return object;
    } else {
        object[array[0]] = objectifyHelper(array.slice(1), object); 
        return object;
    }
}

function objectify(string) {
    const tokens = string.split('.');
    return objectifyHelper(tokens, {});
}

const str = 'user.first.name.robert';
const result = objectify(str);

这让我得到了以下结果:

result <ref *1> {
  name: 'robert',
  first: [Circular * 1],
  user: [Circular * 1]
}

我做错了什么?

推荐答案

你就快到了.然而,如果助手接受一个对象但也返回它,那么在递归调用中要保持一致

function objectifyHelper(array, object) {
    if (array.length === 2) {
        const [key, value] = array;
        object[key] = value;
        return object;
    } else {
        object[array[0]] = objectifyHelper(array.slice(1), {}); 
        return object;
    }
}

function objectify(string) {
    const 到kens = string.split('.');
    return objectifyHelper(到kens, {});
}

const str = 'user.first.name.robert';
const result = objectify(str);

console.log(result)

请注意,这只会改变您的

object[array[0]] = objectifyHelper(array.slice(1), object); 

object[array[0]] = objectifyHelper(array.slice(1), {}); 

Reading OP's comment under the question, I believe it's fair 到 further expand the answer.

Yes, passing the newly created object 到 the recursive function and then returning it is could be simplified. One of possible approaches would be 到 remove the need 到 pass the object in到 the function and just return a newly created object 到 the caller.

因此,简化的版本将是

function objectifyHelper(array) {
    // we always create a new object
    var object = {};
    if (array.length === 2) {
        const [key, value] = array;
        object[key] = value;
    } else {    
        object[array[0]] = objectifyHelper(array.slice(1)); 
    }
    // and return it
    return object;
}

function objectify(string) {
    const 到kens = string.split('.');
    return objectifyHelper(到kens);
}

const str = 'user.first.name.robert';
const result = objectify(str);

console.log(result);

Javascript相关问答推荐

使用JavaScript在ionic Web应用程序中更新.pane和.view的背景 colored颜色

有条件的悲剧

警告!合同执行期间遇到错误[执行已恢复](Base Layer 2)

传递一个大对象以在Express布局中呈现

react/redux中的formData在expressjs中返回未定义的req.params.id

Google图表时间轴—更改hAxis文本 colored颜色

网页自检测外部元素无法加载

如何在Connect 4游戏中 for each 玩家使用位板寻找7形状?

函数返回与输入对象具有相同键的对象

无法从NextJS组件传递函数作为参数'

以编程方式聚焦的链接将被聚焦,但样式不适用

如何限制显示在分页中的可见页面的数量

AddEventListner,按键事件不工作

无法重定向到Next.js中的动态URL

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

使用线性插值法旋转直线以查看鼠标会导致 skip

有没有办法通过使用不同数组中的值进行排序

我为什么要使用回调而不是等待?

REACT-本机错误:错误类型错误:无法读取未定义的容器的属性

正在发出错误的URL请求