I'm new to JS and want to store the table below in a variable. I used dictionary like below. Maybe I'm wrong and it is not good.
<script>
var dict = {}
dict[0]['Name'] = "AD";
dict[0]['Color'] = "Blue";
dict[0]['Year'] = "2020";
dict[1]['Name'] = "DC";
dict[1]['Color'] = "Red";
dict[1]['Year'] = "1809";
dict[2]['Name'] = "FD";
dict[2]['Color'] = "Green";
dict[2]['Year'] = "2011";
console.log(dict);
</script>
and all like that. But I only get the error output.
TypeError: Cannot set properties of undefined (setting 'Name')
I need to feel data like this structure via Javascript. But I'm wrong. why? What is the problem?
See the picture I attached of the table.
First of all, dict
should be an array, rather than an object. Then, you should add the objects to the array. Example:
let dict = [];
dict.push({'Name': 'AD', 'Color': 'Blue', 'Year': '2020'});
console.log(dict);
You need to define the index you try to set as an object. However I would recommend using my example at index 3 instead. Alternatively you can an array
instead of an object
. I assume that you require key value pairs in this case.
var dict = {}
dict[0] = {}
dict[0]['Name'] = "AD";
dict[0]['Color'] = "Blue";
dict[0]['Year'] = "2020";
dict[1] = {}
dict[1]['Name'] = "DC";
dict[1]['Color'] = "Red";
dict[1]['Year'] = "1809";
dict[2] = {}
dict[2]['Name'] = "FD";
dict[2]['Color'] = "Green";
dict[2]['Year'] = "2011";
// I would recommend doing it like this instead
dict[3] = {Name: 'CD', Color: 'Red', Year: '2012'}
console.log(dict);