0

I am trying to add a property to an object, but Dot notation can't handle a string.

my object:

var lists = {
"Cars":{"Ford":false,"Ferarri":false},
"Names":{"John":true,"Harry":false},
"Homework":{"Maths":true,"Science":false,"History":true,"English":true}
} 

Adding a property:

function add_item() {
var input = "Alfa Romeo";
var command = eval('lists.Cars.' +  input + '=false');
}

How can I do this using Bracket Notation seeing as it's a 2D object?

CodeSlow
  • 133
  • 1
  • 7

1 Answers1

1

No need for eval.. and blah is undefined in your example.

var lists = {
  "Cars":{"Ford":false,"Ferarri":false},
  "Names":{"John":true,"Harry":false},
  "Homework":{"Maths":true,"Science":false,"History":true,"English":true}
} 

function add_item(key, value) {
  lists.Cars[key] = value;
}

add_item('Alfa Romeo', true);

console.log(lists);
elzi
  • 5,442
  • 7
  • 37
  • 61