[英]Add dynamic property to existing child properties in javaScript object
I know this sounds simple, but especially in this scenario it is not.我知道这听起来很简单,但在这种情况下尤其如此。 lets say I've an object假设我有一个 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 eg如果我使用最后一种方法添加属性,它可以正常工作,例如
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现在真正的问题在这里,我想将动态属性添加到我的garageForm
object 的garage
属性中,如果我使用上面相同的方法,我不会得到我想要的结果
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现在如果打印我的garagForm
object 的值,它显示如下
{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.这意味着我希望新添加的属性是garageForm.garage
而不是garageForm
本身。
how can I achieve my required output thanks in advance我怎样才能达到我需要的 output 提前谢谢
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'};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.