Brian
Brian

Reputation: 3958

How to overwrite an element in javascript object array

I want to do the following in javascript but there's something about the syntax I'm not understanding here:

var theObj = { foo: val1, bar: val2 }
if ( condition ) {
  theObj[foo] = newVal
  return theObj // returns { foo: val1, bar: newVal } 
}
return theObj // returns { foo: val1, bar: val2 }

Upvotes: 1

Views: 953

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270637

What you have is not an object array, but rather an object literal. Normally, its properties would be accessed as theObj.property, but JavaScript provides an alternative syntax of theObj["property"] when you need to do operations like string manipulation on the property name (like theObj["property_" + numberVar]), or for properties not valid in dot notation (like number properties theObj[12] = "twelve")

If you access the property via [], you would need to quote the string ["foo"], otherwise the parser would be looking for a variable named foo to insert there. However, this simple string property is better accessed with dot notation:

if ( condition ) {
  theObj.foo = newVal
  return theObj // returns { foo: val1, bar: newVal } 
}

Upvotes: 3

Related Questions