skip to Main Content

I have a nested json object, something like this:

{
  "fontweight": {
    "primary": {
      "weight1": {
        "value": "Regular",
        "type": "fontWeights"
      },
      "weight2": {
        "value": "SemiBold",
        "type": "fontWeights"
      }
    },
  }
}

Now, I get a key and value, like this:

{
    key: "fontweight.primary.weight1.value",
    value: "Bold"
}

I need to update the value for the key in my nested json. How can I do so?

4

Answers


  1. This way you can update the value when you know the key

    const obj = {
      "fontweight": {
        .....
    }
    
    obj["fontweight"]["primary"]["weight1"]["value"] = "Bold";
    
    Login or Signup to reply.
  2. you can have a lodash like set function. note that this mutates the original object

    const obj = {
      "fontweight": {
        "primary": {
          "weight1": {
            "value": "Regular",
            "type": "fontWeights"
          },
          "weight2": {
            "value": "SemiBold",
            "type": "fontWeights"
          }
        },
      }
    }
    
    const update = {
        key: "fontweight.primary.weight1.value",
        value: "Bold"
    }
    
    const set = (obj, update) => {
      const {key, value} = update
      const pathArray = key.match(/([^[.]])+/g)
    
      pathArray.reduce((acc, k, i) => {
        if (acc[k] === undefined) acc[k] = {}
        if (i === pathArray.length - 1) acc[k] = value
        return acc[k]
      }, obj)
    }
    
    set(obj,update)
    
    console.log(obj)
    Login or Signup to reply.
  3. If you happen to have lodash in your project already, then just use lodash.set

    Also be carefull, usualy mutation an existing object is not a good idea when you work with frameworks. They rely on wrapper objects comparison.

    Login or Signup to reply.
  4. No Lodash required

    Assuming the nested JSON doesn’t contain the array, you can update JSON value by defining updateValue function which takes parameters data and an object as {key:'....',value:'...'}. That function can be used to copy existing JSON to do some iteration for updating the target key with a new value like this:

    let data = {
      "fontweight": {
        "primary": {
          "weight1": {
            "value": "Regular",
            "type": "fontWeights"
          },
          "weight2": {
            "value": "SemiBold",
            "type": "fontWeights"
          }
        },
      }
    };
    
    let updateValue = (data, obj) => {
      let key = obj.key.split('.');
      let newValue = obj.value;
      let targetObj = data;
      while(key.length > 1) {
        targetObj = targetObj[key[0]]
        key.shift();
      }
      targetObj[key[0]] = newValue;
      return data;
    }
    
    data = updateValue(data, 
      {
        key: "fontweight.primary.weight1.value",
        value: "Bold"
      }
    );
    console.log(data);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search