简体   繁体   English

Javascript:如何更新嵌套的 json,给定关键路径,如 doc.field1.field2 作为字符串

[英]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?有没有更好的方法来实现这一目标?

Don't reinvent the wheel - lodash 's set can do this for you:不要重新发明轮子 - lodashset可以为你做到这一点:

_.set(objToUpdate, 'doc.a1.b1', 'new_value');

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.

相关问题 如何从 Javascript 中的嵌套 JSON 中获取字段? - how to get a field from nested JSON in Javascript? 如何在Javascript中更新嵌套的JSON密钥? - How to update a nested JSON key in Javascript? 如何使用 Mongoose 在给定另一个嵌套字段值的情况下更新嵌套字段? - How can I update a nested field given another nested field value with Mongoose? 如果将键作为字符串给出,如何部分更新嵌套对象? - How to partially update a nested object given the key as a string? 使用javascript通过字符串过滤json的字段 - filtering a field of json by a string with javascript 如何在字符串中的Javascript中访问已解析的JSON中的嵌套键值对 - How to access nested key value pair in parsed JSON in Javascript in string 更新 firebase firestore doc 中的字段,无需手写字段键以更新 Angular - Updating a field inside a firebase firestore doc without hand write the field key to update Angular 如何在 JavaScript 中更新嵌套的 JSON? - How to update nested JSON in JavaScript? 当另一个字段在 html javascript 中更改时更新 json 字段? - update a json field when another field is changed in html javascript? mongodb:更新嵌套字段,由两个变量给定 - mongodb: update nested field, which is given by two variables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM