[英]Javascript: How to update a nested json, given the key PATH like doc.field1.field2 as string
I am trying to update a nested JSON which is given as an input, eg:我正在尝试更新作为输入给出的嵌套 JSON,例如:
{
"doc": {
"a1": {
"b1": 1,
"b2": [
"one",
"two"
]
},
"a2": "xyz"
}
}
The JSON structure is not known. JSON 结构未知。
Field to update is an input string eg: "doc.a2" or "doc.a1.b1" or "doc.a1.b2"要更新的字段是输入字符串,例如:“doc.a2”或“doc.a1.b1”或“doc.a1.b2”
In addition to the path, the old value and a new value is also given as input.除了路径之外,旧值和新值也作为输入给出。 If the value in the path matches the old value, I want to update it with new value.
如果路径中的值与旧值匹配,我想用新值更新它。
I tried with eval()
and seems possible like if path is "doc.a1.b1", then eval(doc['a1']['b1']='new value')
;我尝试使用
eval()
并且似乎有可能,如果路径是“doc.a1.b1”,那么eval(doc['a1']['b1']='new value')
;
But using eval
may lead to security issues.但是使用
eval
可能会导致安全问题。 Is there a better way to achieve this?有没有更好的方法来实现这一目标?
try this尝试这个
var input1 = "doc.a2";
val1 = "val1";
updateVal(obj, input1, val1);
console.log("val1", obj);
function updateVal(obj, input, val) {
let props = input.split(".");
let currObj = obj;
let index = 0;
for (index = 0; index < props.length - 1; index++) {
currObj = currObj[props[index]];
};
currObj[props[index]] = val;
};
Assuming you don't want to rely on a third party library, here is a 5-line proposal (it may need refinement to tackle corner cases such as invalid given path, depending on how you want to handle those cases, eg error, or create the path).假设您不想依赖第三方库,这里有一个 5 行建议(它可能需要改进以解决极端情况,例如给定路径无效,具体取决于您希望如何处理这些情况,例如错误,或创建路径)。
// given: /////////////////////////////////// const obj = { "doc": { "a1": { "b1": 1, "b2": [ "one", "two" ] }, "a2": "xyz" } } const str = "doc.a1.b2" const newValue = ["three"] // do: /////////////////////////////////////// const keys = str.split(".") let ptr = obj while(keys.length>1) ptr = ptr[keys.shift()] ptr[keys.shift()] = newValue // result: /////////////////////////////////// console.log(obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.