0

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. 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. Here's what I have attempted:

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

This however returns that I cannot set a property Name of 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.

1
  • Product { you are missing : here. Commented Feb 29, 2016 at 3:47

3 Answers 3

2

You can create objects very easily in 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' };
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, this worked! I don't understand why Stock.Product.Name = 'Gum'; doesn't work though. Is it not the same thing?
No, because a product hasn't already been defined. I'll expand my answer.
But having var Product = {}; <- is that not defining the Product object?
Thank you so much for all of the clarifications! That was awesome to learn!
2

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;

2 Comments

Although you seem to have "guessed" correctly I still wonder why you would answer something when you don't know what the question is. =]
@AtheistP3ace It wasn't hard to figure out what his intensions were by his code, just didn't understand exactly the way he was asking it, also the title was pretty clear
1

You can initially create the object Product

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

Then add it to the object Stock:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.