JavaScript:通过 ID 设置嵌套对象值 [英] JavaScript: Setting Nested object value by ID

查看:29
本文介绍了JavaScript:通过 ID 设置嵌套对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在 JavaScript 中更新多级对象集合成员的最佳方法是什么

I would like to know what is the best way to update the member of the multilevel object collection in JavaScript

这是我收藏的简化版:

this.Steps = [

{ id: 1, text: "test", childSteps: 
  [
    { id: 2, text: "test"},
    { id: 3, text: "test"},
    { id: 4, text: "test", childSteps: 
    [
           { id: 10, text: "test"},
           { id: 11, text: "test"}
    ]}
    },
    { id: 5, text: "test"},
    { id: 6, text: "test"},
    { id: 7, text: "test"},    
    { id: 8, text: "test"},
    { id: 9, text: "test"}
  ]
}
];

理想的情况是有一个函数被调用,如:

The ideal would be to have a function to be called like:

updateObjectByID(11, 'string to be set');

当我们只有 1 个级别的对象时,这很容易做到.但是当在多级集合上使用递归时,它变得更加困难.

This is easy to be done when we have only 1 level of objects. But when using recursion on multilevel collection its getting much harder.

我目前正在使用一个函数来解析整个集合并构建字符串,例如:

I'm currently using a function that is parsing the whole collection and building string like :

this.Steps[0].childSteps[3].childSteps[1].text == "string to be set"

然后我对该字符串执行 eval() .

and then I do eval() on that string.

我相信可能会有更简洁的解决方案.

I'm sure there might be a much cleaner solution.

使用 eval 使我的班级无法压缩 btw.

Using eval is making my class impossible to compress btw.

任何帮助将不胜感激.

提前致谢

推荐答案

您可以通过 id 构建对象映射以直接访问:

You can build a map of objects by id for direct access:

var map = {};
(function recurse(steps) {
    for (var i=0; i<steps.length; i++) {
        var step = steps[i];
        map[ step.id ] = step;
        if ("childSteps" in step)
            recurse(step.childSteps);
    }
})(this.Steps);

function updateObjectByID(id, string) {
    map[id].text = string;
}

<小时>

对您的代码的评论:您过度编译了很多.当条件 if(obj.id == objId) 满足时,您已经拥有 obj 引用!!!现在绝对不需要搜索它的路径,从中构建一个字符串并对其进行评估.直接赋值给它的属性即可!


A comment on your code: You overcomplified a lot. When the condition if(obj.id == objId) is met, you have your obj reference already!!! Now there is absolutely no need to search for a path to it, build a string from that, and eval it. Just assign directly to its property!

function(steps, objId, value, whatParam, command) {
    if (typeof whatParam == 'undefined')
        whatParam = 'selected';
    $.each(steps, function(index, obj){
        if(obj.id == objId) {
            // removed a lot of unecessary stuff

            // not sure, looks like "value" was evaled sometimes as well
            obj[whatParam] = value;

         } // insert an "else" here if ids are unique
         if (typeof obj.childSteps != 'undefined') {           
             this.setupObjectState(obj.childSteps, objId, value, whatParam, command);
         }
    });
}

这篇关于JavaScript:通过 ID 设置嵌套对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆