2

I can't pass an object property fullName as a parameter of function setData.

Function setData should called after entering a some value in modal window.

I want to set value to user.fullName using function setData.

Example of object user = { fullName: "Full Name", position: "Manager" }

function setData ( data ) {
  var user,
    value = prompt("Value", "");

  if ( localStorage.getItem("user") ) {
    user = JSON.parse( localStorage.getItem("user") );
  }

  user.data = value; // user.fullName = value; - as an example

  if ( value ) {
    localStorage.setItem("user", JSON.stringify( user ) );
    location.reload();
  }
}

document.getElementById("full-name-button").onclick = function() {
  setData( "fullName" );
};

document.getElementById("position").onclick = function() {
  setData( "position" );
};

Help me, how to pass an object property, because i don't know how do this.

2 Answers2

2

To use a runtime-defined property name, use brackets notation, not dot notation:

user[data] = value;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

There are two ways of assigning object properties.

The "static" way (you know the property name): user.fullName = "Bob";

The "dynamic" way (the property name is given by a runtime expression): user['fullName'] = "Bob";

kjaquier
  • 824
  • 4
  • 11