Home > other >  Cannot set properties of undefined (setting 'male')" when setting object value based
Cannot set properties of undefined (setting 'male')" when setting object value based

Time:04-21

Why does it this not work when doing it with one testObject[Object.values(testObject)[0]]=5 works fine but once I add one more it doesn't work.

const testObject = {
  course: "Math",
  gender: "male",
};
const newObject = {};
newObject[Object.values(testObject)[0]][Object.values(testObject)[1]] = 5;
console.log(newObject);

CodePudding user response:

The problem is that newObject[Object.values(testObject)[0]] which translates to newObject.Math is undefined and with the chained [] you first try to read a property newObject.Math which is undefined and JavaScript will not allow you to do that. You need to assign e.g an empty object to newObject.Math to be able to assign this object other properties.

const testObject = {
  course: "Math",
  gender: "male",
};

const newObject = {};
console.log(newObject[Object.values(testObject)[0]]) // undefined
// this tries to read "undefined" which is not possible
//newObject[Object.values(testObject)[0]][Object.values(testObject)[1]]
// to make it work assign it an object
newObject[Object.values(testObject)[0]] = {};
// now you can assign a new property on that object a value
newObject[Object.values(testObject)[0]][Object.values(testObject)[1]] = 5;
console.log(newObject);

CodePudding user response:

This happens because, newObject is an empty object and when we do newObject[Object.values(testObject)[0]][Object.values(testObject)[1]]=5 firstly it woyld grab the first part of the expression which is newObject[Object.values(testObject)[0]] whoes value is undefined as the newObject does not have any key as such. Now js engine would try to get the second part of the expression newObject[Object.values(testObject)[0]][Object.values(testObject)[1]]=5 And it would be translated to something like this undefined.[Object.values(testObject)[1]]=5 and as undefined is not the object so it give the error as cant read the property of undefined

  • Related