How to get all entries of an object in JavaScript

How to get all entries of an object in JavaScript

Object.entries turns an object’s own enumerable string-keyed properties into an array of two-element arrays. Each pair contains the property name followed by its value.

const settings = {
  theme: "dark",
  retries: 3,
  cache: true
};

const entries = Object.entries(settings);
// [["theme", "dark"], ["retries", 3], ["cache", true]]

That’s useful when the work is naturally expressed as a loop over properties. Destructuring keeps the key and value explicit:

for (const [key, value] of Object.entries(settings)) {
  console.log(key, value);
}

Because the result is an array, it also works with array methods. For example, you can select properties by value or build a transformed object:

const enabledSettings = Object.fromEntries(
  Object.entries(settings).filter(([key, value]) => value !== false)
);

const labels = Object.fromEntries(
  Object.entries(settings).map(([key, value]) => [key, String(value)])
);

The pairs are snapshots of the property values at the time Object.entries runs. Changing a value in the returned array does not change the original object, though the values themselves may refer to mutable objects.

Understanding the order of object entries

The order returned by Object.entries is defined, but it isn’t simply the order in which every property was written. Own enumerable string keys are visited with integer-index keys first, in ascending numeric order, followed by the remaining string keys in property-creation order.

const values = {
  zebra: "first",
  10: "ten",
  2: "two",
  alpha: "last"
};

Object.entries(values);
// [["2", "two"], ["10", "ten"], ["zebra", "first"], ["alpha", "last"]]

An integer-index key is a canonical array-index string in the range from 0 through 4294967294. A string that merely looks numeric does not necessarily qualify. For example, leading zeroes, a minus sign, or a decimal point make these ordinary string keys, so they retain their creation order among other string keys.

const values = {
  "01": "leading zero",
  "-1": "negative",
  "3.0": "decimal",
  "3": "index"
};

Object.entries(values);
// [["3", "index"], ["01", "leading zero"], ["-1", "negative"], ["3.0", "decimal"]]

Updating an existing property does not change its position among ordinary string keys. Deleting a property and adding it again creates a new property, placing it after the other ordinary string keys that remain.

const values = { first: 1, second: 2, third: 3 };

values.second = 20;
Object.entries(values);
// [["first", 1], ["second", 20], ["third", 3]]

delete values.second;
values.second = 20;
Object.entries(values);
// [["first", 1], ["third", 3], ["second", 20]]

This ordering can make an object suitable for predictable iteration, but it is not a substitute for choosing a data structure whose semantics match the task. In particular, integer-index keys are reordered numerically regardless of when they were added.

Handling inherited and non-enumerable properties

Object.entries examines only properties that belong directly to the object and are enumerable. Properties found on its prototype are not included, even if they’re enumerable.

const prototype = { inherited: "from prototype" };
const object = Object.create(prototype);
object.own = "on object";

Object.entries(object);
// [["own", "on object"]]

This differs from a for...in loop, which visits inherited enumerable string properties as well. If such a loop is needed, check ownership explicitly before processing each key:

for (const key in object) {
  if (Object.hasOwn(object, key)) {
    console.log(key, object[key]);
  }
}

Object.entries also omits own properties whose enumerable attribute is false. This often applies to properties created with Object.defineProperty, as well as built-in properties such as many methods on a prototype.

const object = { visible: "included" };

Object.defineProperty(object, "hidden", {
  value: "not included",
  enumerable: false
});

Object.entries(object);
// [["visible", "included"]]

When the task requires non-enumerable own string properties, Object.getOwnPropertyNames returns their names, and Object.getOwnPropertyDescriptor can inspect their attributes without reading the property value.

const names = Object.getOwnPropertyNames(object);

for (const name of names) {
  const descriptor = Object.getOwnPropertyDescriptor(object, name);
  console.log(name, descriptor.enumerable, descriptor.value);
}

Neither Object.entries nor Object.getOwnPropertyNames includes symbol-keyed properties. Use Reflect.ownKeys when all own keys are relevant; it returns both string and symbol keys, including non-enumerable ones.

const token = Symbol("token");
const object = { visible: "value", [token]: "symbol value" };

Reflect.ownKeys(object);
// ["visible", Symbol(token)]

Reading entries can also execute user code: the value of an enumerable own accessor is obtained when Object.entries reads it. A getter may have side effects or throw, so enumerating an object is not necessarily a passive inspection.

const object = {
  get status() {
    console.log("getter ran");
    return "ready";
  }
};

Object.entries(object);
// Logs "getter ran"
// [["status", "ready"]]

Choosing the right approach for your data structure

Use an object when the keys describe named fields of a record, such as configuration options or a response with a known shape. In that case, Object.entries is a convenient way to apply a uniform operation to those fields.

const prices = { book: 12, pen: 2, bag: 35 };

const discounted = Object.fromEntries(
  Object.entries(prices).map(([product, price]) => [
    product,
    price * 0.9
  ])
);

If the collection is fundamentally a sequence, use an array instead. Turning an array into entries produces index strings as keys, and array operations such as map express the intent more directly.

const scores = [8, 5, 9];

const adjusted = scores.map(score => score + 1);
// [9, 6, 10]

Object.entries(scores);
// [["0", 8], ["1", 5], ["2", 9]]

A Map is a better fit when keys are not naturally property names, or when they must retain their types. Object property keys are strings or symbols, so a number used as a property name becomes a string. A Map can distinguish the number 1 from the string "1", and can use objects as keys.

const object = {};
object[1] = "number";
object["1"] = "string";

Object.entries(object);
// [["1", "string"]]

const map = new Map();
map.set(1, "number");
map.set("1", "string");

[...map.entries()];
// [[1, "number"], ["1", "string"]]

Maps are also useful when a collection is frequently added to, deleted from, or iterated as key-value pairs. Their iteration order follows insertion order, and their entries remain pairs rather than requiring property-key conversion.

const counts = new Map();

for (const word of words) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}

for (const [word, count] of counts) {
  console.log(word, count);
}

Converting a Map with Object.fromEntries is appropriate only when its keys can safely become object property keys. Distinct map keys can collapse to the same property name after conversion, and symbol keys are the only non-string keys that remain symbols.

const map = new Map([
  [1, "number key"],
  ["1", "string key"]
]);

Object.fromEntries(map);
// { "1": "string key" }

For a set of unique values with no associated values, use a Set rather than encoding membership as object properties. A set can be iterated directly, while an object introduces property-key coercion and a value for each key.

const visited = new Set(["north", "south"]);

visited.add("east");

for (const location of visited) {
  console.log(location);
}

When an object is used as a dictionary for externally supplied keys, ponder its prototype behavior as well as the shape of its data. A Map avoids inherited property names; alternatively, a null-prototype object can be created when object semantics are required.

const dictionary = Object.create(null);
dictionary["__proto__"] = "ordinary key";

Object.entries(dictionary);
// [["__proto__", "ordinary key"]]

Source: https://www.jsfaq.com/how-to-get-all-entries-of-an-object-in-javascript/


You might also like this video

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply