Ernesto G
Ernesto G

Reputation: 545

Trimming all values in object; Error: Cannot set property of undefined

I'm receiving this object from an API:

{
  "id": 10,
  "lectura": "zx71                          ",
  "articulo": "ZX71                          ",
  "ubicacion": "ddd                           ",
  "uds": 5,
  "usuario": null,
  "createD_AT": "2019-12-04T08:19:56.12"
}

I want to trim the values so I have this function:

const trimValues = object => {
  console.log(JSON.stringify(object, null, 2))
  const trimmedProperties = Object.entries(object).reduce(
    (acc, [key, value]) => {
      if (typeof value == "string") {
        return (acc[key] = value.trim());
      }
    },
    {}
  );
  return { ...object, trimmedProperties };
};

The problem is that I'm getting this error message:

core.js:9110 ERROR TypeError: Cannot set property 'lectura' of undefined

The error is returned in this line: return (acc[key] = value.trim());

What am I missing?

Upvotes: 2

Views: 140

Answers (1)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6749

There are 3 main mistakes first one is that in case of value not being a string you did not return anything meaning that the next iteration of the reduce would receive acc===undefined, and second being that return of the assignment call will just return the value of the key instead of entire object, last being that you also have to destructurize the trimmer properties, you can fix it by doing the following

const trimValues = object => {
  console.log(JSON.stringify(object, null, 2))
  const trimmedProperties = Object.entries(object).reduce(
    (acc, [key, value]) => {
      if (typeof value == "string") {
        acc[key] = value.trim();
      }
      return acc
    },
    {}
  );
  return { ...object, ...trimmedProperties };
};

however there really isn't a reason you should combine the untrimmed properties (not strings) with trimmed ones only after iterating over it, instead to simplify it and remove unnecessary iterations you could do the following:

const trimValues = object => {
    console.log(JSON.stringify(object, null, 2))
    return Object.entries(object).reduce((acc, [key, value]) => {
        acc[key] = (typeof value === "string") ? value.trim() : value;
        return acc
    }, {});
};

Upvotes: 3

Related Questions