javascript - 为多维数组中的节点赋值 javascript

标签 javascript json multidimensional-array

我正在尝试为 json 对象中的元素分配一些新值(文本/对象/数组)。我有一个交换函数,它接受 json 对象、一个带有用于检索元素的索引的数组以及用于替换它的值。目前我正在使用 eval,根据一些人的说法,它是“邪恶的”。有没有更好的方法可以在不进行评估的情况下执行此操作,或者在这种情况下评估可以吗?请记住,它必须是动态的,因为数组可能会发生变化。另外,值得注意的是,我正在以编程方式创建数组参数。

//array looks like: ["cluster", "2", "segment", "0", "node", "3"]    
JsonManager.prototype.swap = function(json, array, val){
        var statement = "json";
        for (var i = 0; i < array.length; i++) {
            if(!isNumeric(array[i]))
            {
            statement += "[\"" + array[i] + "\"]";          
            }else{
                statement += "[" + array[i] + "]"   
            }
        }
        statement += " = val";
        eval(statement);
    };

JSON 对象示例:

var customers = {
    "cluster": [{
        "clusterid": "cluster1.1",
        "color": "blue",
        "flights": "784",
        "profit": "524125",
        "clv": "2364",
        "segment": [{
            "segmentid": "segment1.1",
            "color": "green",
            "flights": "82",
            "profit": "22150",
            "clv": "1564",
            "node": [{
                "nodeid": "node1.1",
                "color": "orange",
                "xpos": "1",
                "ypos": "1"
            }, {
                "nodeid": "node1.2",
                "color": "blue",
                "xpos": "1",
                "ypos": "2"
            }, {
                "nodeid": "node1.3",
                "color": "orange",
                "xpos": "1",
                "ypos": "3"
            }, {
                "nodeid": "node1.4",
                "color": "orange",
                "xpos": "1",
                "ypos": "4"
            }]
        }, {
            "segmentid": "segment1.2",
            "color": "red",
            "flights": "2",
            "profit": "2150",
            "clv": "1564",
            "node": [{
                "nodeid": "node2.1",
                "color": "tan",
                "xpos": "2",
                "ypos": "1"
            }, {
                "nodeid": "node2.2",
                "color": "tan",
                "xpos": "2",
                "ypos": "2"
            }, {
                "nodeid": "node2.3",
                "color": "tan",
                "xpos": "2",
                "ypos": "3"
            }, {
                "nodeid": "node2.4",
                "color": "tan",
                "xpos": "2",
                "ypos": "4"
            }]
        }]
    }, {
        "clusterid": "cluster1.2",
        "flights": "4",
        "profit": "5245",
        "clv": "2364",
        "segment": [{
            "segmentid": "segment1.2",
            "flights": "2",
            "profit": "2150",
            "clv": "1564",
            "node": [{
                "nodeid": "node3.1",
                "xpos": "3",
                "ypos": "1"
            }, {
                "nodeid": "node3.2",
                "xpos": "3",
                "ypos": "2"
            }, {
                "nodeid": "node3.3",
                "xpos": "3",
                "ypos": "3"
            }, {
                "nodeid": "node3.4",
                "xpos": "3",
                "ypos": "4"
            }]
        }]
    }, {
        "clusterid": "cluster1.3",
        "flights": "10",
        "profit": "456978",
        "clv": "548",
        "segment": [{
            "segmentid": "segment1.3",
            "flights": "2",
            "profit": "2150",
            "clv": "1564",
            "node": [{
                "nodeid": "node4.1",
                "xpos": "4",
                "ypos": "1"
            }, {
                "nodeid": "node4.2",
                "xpos": "4",
                "ypos": "2"
            }, {
                "nodeid": "node4.3",
                "xpos": "4",
                "ypos": "3"
            }, {
                "nodeid": "node4.4",
                "xpos": "4",
                "ypos": "7"
            }]
        }]
    }]
};

这是我的测试方法:

JsonManager.prototype.init = function(){
    var clause = new Clause("nodeid", "node4.4");
    var indexes = this.search(customers, clause);
    this.swap(customers, indexes.reverse(), {"name": "kevin"});
    var test = customers["cluster"][2]["segment"][0]["node"][3];  //hard coded pointer to node4.4
    var breakPoint = "breakpoint";  //Just used as a point to stop the debugger to see test
};

为了供将来引用,这里是进一步评论的解决方案:

JsonManager.prototype.swap = function(obj, path, value) {

   //This is the inner function we are recursing into 
   function descend(obj, path) {
    /*This if statement is used to stop the recrusion,
    when we have iterated through all the paths, it returns
    the object above our desired object */
        if (path.length == 0) {
            return obj;
        }
    /*Recurse into the function passing in the top level object and remove
    the top level object from our path*/ 
        return descend(obj[path[0]], path.slice(1));
    }
//Pass in the object and the (path - the last element)
    var node = descend(obj, path.slice(0, -1));
//Get the last node in path, pull it from node and assign the value
    node[path[path.length - 1]] = value;
};

最佳答案

您的“JSON”对象只是一个 JavaScript 对象。更重要的是,它是一棵树,而树最容易使用递归来遍历。

JsonManager.prototype.swap = function(obj, path, value) {
    function descend(obj, path) {
        if (path.length == 0) {
            return obj;
        }
        return descend(obj[path[0]], path.slice(1));
    }

    var node = descend(obj, path.slice(0, -1));
    node[path[path.length - 1]] = value;
};

slice将从数组中取出一 block 。因此,path.slice(1) 返回不带第一个元素的 path,而 path.slice(0, -1) 返回不带最后一个元素的 path一。这意味着我们下降到对象的倒数第二个节点,然后使用普通数组表示法设置最后一个节点。理解它的最简单方法是使用上面的示例在纸上手动完成它。

关于javascript - 为多维数组中的节点赋值 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6001578/

相关文章:

java - 在recyclerView中获取json数据

c# - 如何在 MVC Controller 中访问 Javascript 多维数组

c - 简短快速的 malloc 内存访问问题

c# - DataContract + 多维数组——有什么解决方案吗?

javascript - AMP 广告 : How to configure dynamic DFP key-value in json property

javascript - 简化 Javascript 中的 text.replace()

javascript - 单击 React 在新窗口中打开组件

javascript - 有时未设置内联样式的 background-position-x 或 y 属性

jquery - 通过 getJSON 将 get 变量发送到 php 文件?

javascript - 向外部站点提供 javascript 文件时没有 'Access-Control-Allow-Origin'