niklassc
niklassc

Reputation: 550

Object.create() says parameter is not an object

Description

In my program I am reading a JSON file, parsing it into an object and then I try to "cast" it into an object of the class ProjectFile using Object.create().

Code

let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf-8'});
let tmpObject = JSON.parse(tmpFileContent);
console.log(tmpObject);
fileList[fileList.length] = Object.create(ProjectFile, tmpObject);

Log

log

Question

When I output tmpObject using console.log(tmpObject); it says that it is an object in the log. In the line after that I try to use it as object which should be casted into an object of the class ProjectFile but it displays the error message that it is not an object. What am I doing wrong?

Edit: ProjectFile class

class ProjectFile {
  constructor(p_name, p_path, p_type, p_thumnailPath) {
    this.name = p_name;
    this.path = p_path;
    this.thumnailPath = p_thumnailPath;
  }
}

Edit 2: Working code

let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf-8'});
          let tmpObject = JSON.parse(tmpFileContent);
          console.log(tmpObject);
          fileList[fileList.length] = Object.create(ProjectFile, {
            name: {
              value: tmpObject.name,
              writable: true,
              enumerable: true,
              configurable: true
            },
            path: {
              value: tmpObject.path,
              writable: true,
              enumerable: true,
              configurable: true
            },
            thumnailPath: {
              value: tmpObject.thumnailPath,
              writable: true,
              enumerable: true,
              configurable: true
            }
          });

Upvotes: 0

Views: 87

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68655

Object.create function gets the prototype as the first parameter and property descriptors as the second parameter.

Your second parameter has wrong type. You need to pass an object, which contains objects with property attributes which are configurable, writable, enumerable and the value for it.

See the example. In the second case when I pass an parameter which does not apply for the desired shape, it gives me the same error.

const pr = { name: 'Name' };
const successChild = Object.create( pr, {
  surname: {
    value: 'Surname',
    writable: true,
    enumerable: true,
    configurable: true
  }
});

console.log(successChild);

const errorChild = Object.create( pr, {
  name: 'Error Name',
  surname: 'Error Surname'
});

Upvotes: 3

Related Questions