简体   繁体   English

JavaScript-将对象添加到对象

[英]JavaScript - Adding an object into an object

I do realise this has been asked before but I cannot find the exact answer to my question. 我的确知道之前曾有人问过这个问题,但我找不到我问题的确切答案。

I'm trying to recreate an object in JavaScript. 我正在尝试在JavaScript中重新创建对象。 The original object looks like this: 原始对象如下所示:

Stock {
   Id: 'a0236000374782',
   Product { Name: 'Gum',
             Price: 2.49
           }
}

When I attempt to recreate the stock object I already have the first value Id in it and I am trying to somehow push the Product object in it as well. 当我尝试重新创建库存对象时,我已经在其中有了第一个值Id,并且试图以某种方式将Product对象也推入其中。 Here's what I have attempted: 这是我尝试过的:

var Product = {};
Stock.Product.Name = 'Gum';

This however returns that I cannot set a property Name of undefined. 但是,这返回我无法将属性名称设置为undefined的问题。 I also tried: 我也尝试过:

var Product = {};
stock = {Product.Name : 'Gum'};

This returns "Uncaught SyntaxError: Unexpected token ".". I cannot figure out what am I not doing right. 这将返回“未捕获到的SyntaxError:意外的令牌”。我无法弄清楚我在做什么不正确。

Not sure what you're asking but I think you want something like this 不知道你在问什么,但我想你想要这样的东西

var Stock = {
    Id: 'asdasdasd',
    Product: {
       Name: 'Gum',
       Price: '2.49'
    }
};

Or 要么

var Stock = {
    Id: 'asdasdasd'
}

var Product = {
    Name: 'Gum',
    Price: '2.49'
}

Stock.Product = Product;

You can create objects very easily in JavaScript. 您可以使用JavaScript非常轻松地创建对象。

Assuming you already have stock defined looking something like this: 假设您已经定义了库存,如下所示:

var stock = { id: '1234' };

You can then assign a product as follows: 然后,您可以按以下方式分配产品:

stock.product = { name: 'Gum', price: 2.49 };

That's the same as doing this: 这与执行此操作相同:

var product = { name: 'Gum', price: 2.49 };
stock.product = product;

But you can't assign a property onto an object that hasn't already been created. 但是您不能将属性分配给尚未创建的对象。 So this isn't possible: 因此这是不可能的:

stock.uncreatedObject.myProp = 'Will not work'; 

But this is possible: 但这是可能的:

stock.createdObject = {};
stock.createdObject.myProp = 'This will work';

Which is equivalent to this: 这等效于:

stock.createdObject = { myProp: 'Will Work' };

You can initially create the object Product 您可以最初创建对象Product

var Product = {Name: "", Price: ""};

Then add it to the object Stock : 然后将其添加到对象Stock

var Stock = {Id: "", Product};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM