gpt4 book ai didi

javascript - 如何使用字符串访问嵌套对象值以便我可以编辑?

转载 作者:行者123 更新时间:2023-11-28 14:33:38 33 4
gpt4 key购买 nike

如果我有以下字符串或数组:

var thestring = '[0]["more"][0]["more"][0]["text"]';
var thearray = ['0','more','0','more','0','text'];

如何使用该字符串或数组来标识对象的一部分以便对其进行编辑?

var theobject = [
{
"id":1,
"text":"hello",
"more": [
{
"id":2,
"text":"hello",
"more":[
{
"id":3,
"text":"hello", // I want to edit this
"more": [
{
"id":4,
"text":"hello",
"more":[
]
}
]
}
]
}
]
},
{
"id":5,
"text":"hello"
},
{
"id":6,
"text":"hello"
},
{
"id":7,
"text":"hello"
}
];

基本上我正在尝试访问对象的这一部分:

theobject[0]["more"][0]["more"][0]["text"];

但是如果我用字符串来做它就不起作用:

theobject[thestring];

最佳答案

如果您不需要依赖项,此函数将更新thearray描述的值:

function setObjectValue(o, a, v) {
a = a.slice(); // copy array
p = a.pop(); // get last value for updating
a.forEach(function(p) { o = o[p]; }); // traverse object for each property in a
o[p] = v; // update the final value
}

用法:setObjectValue(theobject, thearray, 'UPDATED')

关于javascript - 如何使用字符串访问嵌套对象值以便我可以编辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50588807/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com