0

I'm trying to dynamically add object values using a type variable.

Here is a working example without using a type variable:

let test = {
    'details': {
        'address': {
            'line1': '13 test st'
        }
    }
}

test['details']['address']['line1'] = '18 test st'

console.log('test', test)

The test variable successfully has a new line1 of '18 test st'. However, I want to be able to use a type variable, which fails:

let type = `['details']['address']['line1']`

`${test}${type}` = '20 test st'

How can this be achieved? I know my syntax is incorrect but I can't find anywhere that defines how this can be achieved.

user8758206
  • 2,106
  • 4
  • 22
  • 45

2 Answers2

1

You can store the key in an array and access it like below.

const test = {
  details: {
    address: {
      line1: "13 test st",
    },
  },
};

console.log(test);

const type = ["details", "address", "line1"];

test[type[0]][type[1]][type[2]] = "20 test st";

console.log(test);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
1

You can use regex to extract key name and then using array#reduce iterate through each key and create object and for the last key assign your value.

const test = {},
      value = '18 test st',
      path = `['details']['address']['line1']`;
path.match(/\w+/g).reduce((o, key, i, a) => {
  o[key] ||= {};
  if(i === a.length - 1) {
    o[key] = value;
  }
  return o[key];
}, test);
console.log(test);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51