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

查看:109
本文介绍了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天全站免登陆