Skip to main content

Command Palette

Search for a command to run...

Prevent an object key from appearing in `Object.keys()` or `for..in` loop

Published
1 min read
const obj = { name: "Human", age: 26, location: "World", role: "Developer" };

console.log(Object.keys(obj)); // [ 'name', 'age', 'location', 'role' ]

// Updating setting for `name` property 
Object.defineProperty(obj, "name", {
  enumerable: false,
});

console.log(Object.keys(obj)); // [ 'age', 'location', 'role' ]

const objKeys = [];
for (const key in obj) objKeys.push(key);

console.log(objKeys); // [ 'age', 'location', 'role' ]
P

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
let unorderedData = {
  real_name: 'Millie Bobby Brown',
  character_name: 'Eleven',
  series: 'Stranger Things'
};
console.log(JSON.stringify(unorderedData));

const orderedData = {};
Object.keys(unorderedData).sort().forEach(function(key) {
  orderedData[key] = unorderedData[key];
});

console.log(JSON.stringify(orderedData));

More from this blog

Codedrops.tech

49 posts