TypeError: Cannot convert undefined or null to object

I have a error about delete this.datastore[key]. I tried to solve the problem. I removed the ‘[key]’ but return wrong value. I want to see Number of entries: 0 at last output. What is the problem ? Thanks for helping comments.

function clear(){
	Object.keys(this.datastore).forEach(function(key, index) {
		delete this.datastore[key];
	});
}

Full Code:

// Updates the complete Dictionary class definition

function Dictionary(){
	this.add = add;
	this.datastore = new Array();
	this.find = find;
	this.remove = remove;
	this.showAll = showAll;
	this.count = count;
	this.clear = clear;
}

function add(key, value){
	this.datastore[key] = value;
}

function find(key){
	return this.datastore[key];
}

function remove(key){
	delete this.datastore[key];
}

function showAll(){
	var datastore = this.datastore;
	Object.keys(this.datastore).forEach( function(key, index) {
       console.log(key + " -> " + datastore[key]);
    });
}

function count(){
	var n = 0;
	Object.keys(this.datastore).forEach( function(key, index) {
		++n;
	});
	return n;
}

function clear(){
	Object.keys(this.datastore).forEach(function(key, index) {
		delete this.datastore[key];
	});
}


// Using the count() and clear() functions

var pbook = new Dictionary();
pbook.add("Raymond", "123");
pbook.add("David", "345");
pbook.add("Cynhia", "456");
console.log("Number of entries: " + pbook.count());
console.log("David's extension: " + pbook.find("David") + "\n");
console.log("-------------------------");
pbook.showAll();
pbook.clear();
console.log("Number of entries: " + pbook.count());

Hi snntaylan,

I think that in the clear function, you have to bind “this” to the originating context. So, using an arrow function or declaring datastore like in the “showAll” function could resolve your problem.

function clear(){
	Object.keys(this.datastore).forEach( (key, index) => {
		delete this.datastore[key];
	});
}

Or

function clear(){
  let datastore = this.datastore;
	Object.keys(this.datastore).forEach( function(key, index) {
		delete datastore[key];
	});
}

Can you please keep to one topic in future, you don’t need to make a new one if it’s for the same problem :wink:

Again, same answer as the last time, you are using an array as the data store, this can’t work, it’s the wrong data structure. Arrays look like this:

['a', 'b', 'c']

You can’t set the keys to things that are not indices: an array cannot have a value “123” at index “Raymond”, that’s nonsensical

1 Like