Home > Net >  How can I show the unenumerable property id when printing the object to the console
How can I show the unenumerable property id when printing the object to the console

Time:01-09

I have a simple task here that requires me not to make the id enumerable but at the same time, it should be shown when logging the object in the console how can I achieve that when I have to make the property descriptor enumerable false?

const myObj = {
  username: "Elzero",
  id: 100,
  score: 1000,
  country: "Egypt",
};

// Write Your Code Here

Object.defineProperty(myObj, 'id', {enumerable: false});


for (let prop in myObj) {
  console.log(`${prop} => ${myObj[prop]}`);
}

console.log(myObj); 

// Needed Output

// "username => Elzero"
// "score => 1000"
// {username: 'Elzero', score: 1000, id: 100}

CodePudding user response:

const allProperties = Object.getOwnPropertyNames(myObj).reduce((prev, curr) => {
  prev[curr] = myObj[curr];
  return prev;
}, {});

console.log(allProperties);

The Object.getOwnPropertyNames() static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.

Id property will be included in allProperties even if it is set as non-enumerable.

CodePudding user response:

enter image description herei am not sure what you want to do here but i think your code has this result already

script.js:61 username => Elzero
script.js:61 score => 1000
script.js:61 country => Egypt
script.js:64 {username: 'Elzero', score: 1000, country: 'Egypt', id: 100}

so please try to clarify your question in order to help

  • Related