0

I have a requirement wherein I get nested object keys in an array. I have an array of keys like

let keys = ["vehicleInformation", "VehicleBlock|1", "DriverAssociation|1", "DriverInvolvedAssociation"]

There is already a JSON data that is stored in a variable and I have to update a data object.

data['vehicleInformation']['VehicleBlock'][1]['DriverAssociation'][1]['DriverInvolvedAssociation'] = value;

Is there a way to achieve this in javascript? Initial value of data:

data = {};

Expected result:

data = {
  vehicleInformation: {
    VehicleBlock: [
      {},
      {
        DriverAssociation: [
          {},
          {DriverInvolvedAssociation: value},
        ],
      },
    ],
  },
};
Rohan Shenoy
  • 805
  • 10
  • 23
  • 1
    Your description was pretty minimal, but if what you're interested in is changing a variable nested deep in an object, this looks pretty handy: https://stackoverflow.com/a/50392139/1772933 – Kinglish May 27 '21 at 03:54

1 Answers1

1

keys = ["vehicleInformation", "VehicleBlock|1", "DriverAssociation|1", "DriverInvolvedAssociation"]
data = {
  vehicleInformation: {
    VehicleBlock: [
      0,
      {
        DriverAssociation: [
          0,
          {},
        ],
      },
    ],
  },
};

let value = 42;
let keysToLast = keys.flatMap(key => key.split("|"));
let lastKey = keysToLast.pop();
keysToLast.reduce((a, e) => a[e], data)[lastKey] = value;
console.log(data);

Array keys are just strings like object keys, no reason to treat them differently (thus flatMap). Then just reduce to find the object whose property you need to set, and set it.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • why to use `flatMap` then finding the `lastKey` and then `reduce`. When you can do exactly same with `reduce`. CODE =>> `keys.reduce((acc, curr, index, arr) => { const [key, i] = curr.split("|"); if (index === arr.length - 1) return (acc[key] = value); if (!i) { acc = acc[key]; } else { acc = acc[key][i]; } console.log(acc); return acc; }, data);` – DecPK May 27 '21 at 04:05
  • @decpk Sure, you can, but I feel my way to be more general (and `flatMap` only serves to satisfy the OP's artificial separation of array and object keys, and prepare for the general operation of digging into a data structure). The same logic for taking the last key out - the operation of digging to the next-to-last key for writing and digging to the last key for reading are completely equivalent. – Amadan May 27 '21 at 04:18