0

I know this sounds simple, but especially in this scenario it is not. lets say I've an object

let garageForm = {}

I know If I want to add property I can use the following methods

Object.defineProperty(params...)
Obj.property=value
Obj[prop]=value

if I add property using the last method it works fine e.g.

let key='garage'
let garageDetails = {
    nameEnglish:'Mirqab',
    others:'someProps',
}
garageForm[key]=garageDetails

//outputs of garageForm is as follows
garage: {nameEnglish: "Mirqab", others: "someProps"}

Now the real problem for lies here, I want to add the dynamic properties to to garage property of my garageForm object, If I use the same method above I don't get my desired results

let ownerKeyName = 'garage.owner'
let ownerValue = {name: 'foo',phone: '123'}
garageForm[ownerKeyName] = ownerValue

Now if print the value of my garagForm object, it shows like this

{garage: {…}, garage.owner: {…}}

whereas, I want my results to look like this

garage: {nameEnglish: "Mirqab", others: "someProps", owner: {…}}

meaning that I want the newly added property to be the of garageForm.garage and not the garageForm itself.

how can I achieve my required output thanks in advance

hsdmedia
  • 3
  • 2
  • There's no built-in functionality for this in JS, you have to either use something like `lodash/set` (https://docs-lodash.com/v4/set/), or implement the same by yourself. – Nikita Ivanov May 24 '21 at 09:42
  • Does this answer your question? [Accessing nested JavaScript objects and arrays by string path](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path) – evolutionxbox May 24 '21 at 09:45

1 Answers1

0

You can do something like this:

let garageDetails = {
    nameEnglish:'Mirqab',
    others:'someProps',
}
const garageForm = { garage: garageDetails };
garageForm.garage.owner = {name: 'foo',phone: '123'};

If you need the dynamic values:

let garageDetails = {
    nameEnglish:'Mirqab',
    others:'someProps',
}
const key='garage';
const garageForm = {};
garageForm[key] = garageDetails;

const ownerKey = 'owner';
garageForm[key][ownerKey] = {name: 'foo',phone: '123'};
Virtuoz
  • 896
  • 1
  • 8
  • 14