0

This is probably a simple answer but i am still learning so here i go. I have an object shade which you can see below. I also have a html value element which i am trying to split the value and place it into my object.

However its trying to add to shade.color.fill which doesnt exitst i need it to add to shade.color.cord instead.

value="type|Color"

Javascript

var obj = {
    color: {
        Type: null
    }
}

var fill = this.getAttribute('value').split("|");
shade.color.fill[0] = fill[1];
console.log(obj.type.color);

error:

TypeError: obj.type.fill is undefined
5
  • fill[0] = cord so your value will assign to shade.color.cord and you are accessing shade.color.fill which will give you undefined as error Commented May 18, 2016 at 7:33
  • @Apb You are Correct, however i am trying to add the fill[1] value into the object shade.color.cord and cord should be the value of fill[0] Commented May 18, 2016 at 7:34
  • Yes. So what is problem? Commented May 18, 2016 at 7:35
  • Try: shade.color.fill = [fill[1]]; Commented May 18, 2016 at 7:36
  • @Apb the problem is that fill[0] value is a dynamic value so it can be "cord" or "trim" etc.. so i need it to write the fill[1] value to shade.color.cord instead. For example lets say i have trim|TT-399 Mood Indigo then it would write to shade.color.trim instead. does this make sense? Commented May 18, 2016 at 7:40

1 Answer 1

2

If you need to do what I think you need to do, this should work (use square bracket notation as opposed to dot notation in order to set the name dynamically):

var shade = {
    color: {
        cord: null
    }
}

var fill = this.getAttribute('value').split("|");
shade.color[fill[0]] = fill[1];
console.log(shade.color.cord);
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect thanks what is the difference between the square to the dot notation?
@Elevant Square bracket notation accepts a string value as a key whereas dot notation accepts the name explicitly. Since you were setting the name from a string value you needed square brackets.

Your Answer

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