Sonhja
Sonhja

Reputation: 8448

Cannot assign to read only property 'whatever' of object #<Object>?

I have the following code:

let filteredArray = data
        .filter((object) =>
            isFilterInArray(filterBy, Object.values(object))
        )
        .forEach((object) => {
            Object.keys(object).forEach((key) => {
                object[key] = markHighlightedText(filterBy, object[key]);
            });
        });

It should be filtering initially the items that an array contains based on a filterBy value.

Once I filter it, I'm trying to modify each value and do some stuff, but then the

object[key] = markHighlightedText(filterBy, object[key]);

is failing with the following error:

enter image description here

Why is this wrong?

Upvotes: 0

Views: 1940

Answers (1)

Raz Luvaton
Raz Luvaton

Reputation: 3770

It looks like you’re trying to change non-configurable property attributes

A TypeError is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted) unless the current and new values are the same.

From MDN - Modifying a property

And because you got the key from Object.keys it’s mean the property is also enumerable

The enumerable property attribute defines whether the property is picked by Object.assign() or spread operator. For non-Global_Objects/Symbol properties it also defines whether it shows up in a for...in loop and Object.keys() or not.

From MDN - Modifying a property - Enumerable attribute

Mapping it to a new object as epascarello commented, will fix that issue


let filteredArray = data
  .filter((object) => isFilterInArray(filterBy, Object.values(object)))
  .map((object) => {
      // We are creating new object and not assigning to the original one because
      // some object keys aren’t writable (can’t assign to them)
      // but enumerable - meaning we get them in the Object.keys
      return Object.keys(object).reduce((newObject, key) => {
        newObject[key] = markHighlightedText(filterBy, object[key]);
        return newObject;
      }, {});
  });

Upvotes: 1

Related Questions