+
95
-

js中如何根据多级索引数值来获得多级数组的元素?

js中如何根据多级索引数值来获得多级数组的元素?例如下面一个无限级评论数组,如果根据[0,1]找到数组第一级的index为0的数组下的replydata的index为1的元素?并且是引用传值,修改data会影响之前的结果。

let data = [
    {
        "id": 1,
        "pid": 0,
        "topicid": "16936077025814910031",
        "zannum": 0,
        "uid": 1,
        "atime": 1693732973,
        "words": "你好",
        "replynum": 0,
        "replydata": []
    },
    {
        "id": 2,
        "pid": 0,
        "topicid": "16936077025814910031",
        "zannum": 0,
        "uid": 1,
        "atime": 1693732982,
        "words": "你好鲜牛奶",
        "replynum": 1,
        "replydata": [
            {
                "id": 3,
                "pid": 2,
                "topicid": "16936077025814910031",
                "zannum": 0,
                "uid": 1,
                "atime": 1693735364,
                "words": "你就",
                "replynum": 0,
                "replydata": []
            }
        ]
    }
];

const indexes = [0, 1]; // 例如,获取第一个元素的第二个元素
const result = getValueByIndexArray(data, indexes);
console.log(result)
result.replynum=111;

console.log(data)


网友回复

+
15
-

可以用eval

const indexes = [0, 1]; //
let evalCode = 'data';
 ...

点击查看剩余70%

我知道答案,我要回答