2

Below is my json content

{
    "demoPO":{
      "login":["demoJPLog in", "demoFRLog in","GELog in"],
      "cancel":["demoJPCancel", "demoFRcancelo","GEcancelo"],
      "content":["demoJPcontent", "demoFRcontent","GEcontent"]
    },
    "demoPO2":{
      "login":["JPLog in", "FRLog in","GELog in"],
      "cancel":["JPCancel", "FRcancelo","GEcancelo"],
      "content":["JPcontent", "FRcontent","GEcontent"],
      "submit":["JPsubmit", "FRsubmit","GEsubmit"]
    }
}

I want to update value of key demPO2.login[0]

data.demoPO2.login[0] = value; //this updates key - works

consider user is passing **key** as a variable

var keyName = 'demPO2.login[0]'
data[keyname] = value; //doesn't update, adds a new one

Is there a way to overcome this where user can pass key as variable and update when there are multi-level array in json?

sridattas
  • 459
  • 1
  • 6
  • 21
  • WHat will be key here? You are updating an array and not object. If you pass demPO2 that is fine but passing demPO2.login[0] as key is not a feasible solution – Harmandeep Singh Kalsi Jun 29 '20 at 06:45

2 Answers2

1

You can use lodash _.set method.

import _ from "lodash";

_.set(data, "demoPO2.login[0]", "test1");

0

You should extract path to element from key to be ["demPO2", "login", "0"], and then loop it:

var json = {
    "demoPO":{
      "login":["demoJPLog in", "demoFRLog in","GELog in"],
      "cancel":["demoJPCancel", "demoFRcancelo","GEcancelo"],
      "content":["demoJPcontent", "demoFRcontent","GEcontent"]
    },
    "demoPO2":{
      "login":["JPLog in", "FRLog in","GELog in"],
      "cancel":["JPCancel", "FRcancelo","GEcancelo"],
      "content":["JPcontent", "FRcontent","GEcontent"],
      "submit":["JPsubmit", "FRsubmit","GEsubmit"]
    }
};

function extract(key) {
  var keys = key.split('.');

  var current = json;

  for (var i = 0; i < keys.length; i++) {
     if (typeof current[keys[i]] === 'undefined') {
        return null;
     }

     current = current[keys[i]];
  }
  
  return current;
}

// For simplicity we assume key is `.` separated

console.log(extract('demoPO2.login.0'));
console.log(extract('demoPO2.content.2'));
console.log(extract('demoPO2.key.notExists'));
Justinas
  • 41,402
  • 5
  • 66
  • 96