0

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}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • _"Needed Output"_ is missing the `country` property – Andreas Jan 09 '23 at 12:47
  • "*I have a simple task here*" - do you mean this is some sort of exercise? Or something you want to achieve yourself? – Bergi Jan 09 '23 at 12:49
  • 2
    What environment are you executing this code in, what `console` implementation are you using? E.g. browser devtools *do* show non-enumerable properties by default. – Bergi Jan 09 '23 at 12:49
  • @Bergi _"// Write Your Code Here"_ - I would guess the first option. – Andreas Jan 09 '23 at 12:50
  • 2
    You cant mix `non-enumerable` and `for-in` loop. For loops use `Object.getOwnPropertyNames(myObj)` which return array of keys. Look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties – Jan Pfeifer Jan 09 '23 at 12:52

1 Answers1

0
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.

Safal Pillai
  • 1,567
  • 1
  • 16
  • 31