-1

I have an object which I am trying to get an array of the values of, however whenever I run Object.values(), it returns an empty array. I also get an empty array when I run Object.keys() or Object.entries(). Also when I try and loop through the properties of the array (Like so: for(var property in object){}), it runs 0 times, like there are no keys/values in the object.

The object itself is definitely not empty at the time of running Object.values, as to debug this issue, I had the result of Object.values logged to the console(which was an empty array), and on the line before that, I had the object logged to the console, and the object was not empty. The properties of the object are also accessible by using objectName.propertyName, or objectName["propertyName"]. The object's keys are strings and its values are arrays. The objects properties were defined by Object.defineProperty().

I am using the React framework.

According to tests I ran in a js console, this should not be happening.

Does anyone know why this is happening and how to fix it?

Please let me know if you would like me to provide any information or code.

4
  • Can you include a Minimal, Complete, and Reproducible Code Example in your question. It's very difficult to help debug phantom code. My guess would be that at some point the React component lifecycle the object is actually empty and only populated via mutation and when console logged you can see the mutated value. Commented May 29, 2021 at 4:44
  • "The objects properties were defined by Object.defineProperty()" - you need to ensure you make the keys enumerable, by default it is false Commented May 29, 2021 at 4:44
  • See: Strange behavior of Object.defineProperty() in JavaScript Commented May 29, 2021 at 4:47
  • 1
    @NickParsons Thank you so much! I believed that they were enumerable by default, not sure why, as it says in the docs they are not enumerable by default. Commented May 29, 2021 at 4:47

1 Answer 1

-1

You may be forgetting the set enumerable true on the property description, see the next example how foo doesn't appear on keys but bar does.

const obj = {};
Object.defineProperty(obj, 'foo', {});
Object.defineProperty(obj, 'bar', { enumerable: true });

console.log(Object.keys(obj));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.