1

I know this is very basic but i just can't solve it. I simply need to add a field to an object inside an object.

   var shipping = {}
   shipping["only"]["price"]  = $(this).val();

Keep saying that i can't set price of undefined.

Everywhere i checked, i am allowed to do this nested assignment.

5
  • 3
    means shipping["only"] is undefined. And looking at your shipping object, there is no properties in it. Commented May 26, 2020 at 18:50
  • try this :var shipping = {only:{}} shipping["only"]["price"] = $(this).val(); Commented May 26, 2020 at 18:57
  • What is the problem with shipping.only = {price : $(this}.val()}; ? Commented May 26, 2020 at 19:02
  • @VahidAlimohamadi because i dont want to override .only, it might be already exist, or might not, and i want to update it. Commented May 28, 2020 at 8:49
  • so you can: shipping.only = { ...shipping.only, price: $(this).val() } Commented May 28, 2020 at 10:09

2 Answers 2

1

You've got the semantics wrong for what your code means. This:

shipping["only"]["price"] = $(this).val();

...sort of translates to:

  1. Evaluate $(this).val() (we'll call this R for the sake of convenience)
  2. Evaluate shipping["only"] (we'll call this O)
  3. Assign the price property of O to the value R.

On step 2, because shipping is the value {}, shipping["only"] is undefined, and this is why you get the error that it can't assign to the property price of undefined.

If your intent is to create an object only property and set the price value of that new object, you'll want to do something more like:

const shipping = {
  only: {
    price: $(this).val()
  }
};

...or you can do two assignment statements, one to populate .only and then one to populate the sub-property:

shipping.only = {};
shipping.only.price = $(this).val();
Sign up to request clarification or add additional context in comments.

2 Comments

thanks Jacob, the thing is that this object is dynamic and global, and i don't want to rewrite it , just to add a field. How can i add a field to an existing object without override it?
I'm not quite sure what you're asking. Perhaps you mean you don't know whether a property already exists or not? If that's the case, check if the property exists before overwriting. For example shipping.only = shipping.only || {}, or the less esoteric if (!shipping.only) shipping.only = {};
1

You can use defineProperty()

var shipping = {}

Object.defineProperty( shipping, 'only', {

    value: { price: $(this).val() },
    writable: true,
    enumerable: true,
    configurable: true

});

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.