ghostagent151
ghostagent151

Reputation: 1406

Why does this function throw an error when using the includes method?

I'm having trouble figuring out why this function throws an error when it reaches the 'includes' method, when console logging whitelist, it shows that it is an array, when i use the includes method, it is throwing an error, cannot read property includes of undefined

const test = (body, ...whitelists) => {
  const bodies = whitelists.map(({ type = null, whitelist }) => {
    console.log('whitelist ', whitelist)

    const whitelistedBody = Object.entries(body).reduce(
      (newBody, [key, value]) => {
        console.log('KEY ', key)
        console.log('whitelist ', whitelists)

        if (whitelist.includes(key)) {
          newBody[key] = value;
        }

        console.log('newBody ', newBody)
        return newBody;
      },
      {}
    );

    return { type, body: whitelistedBody };
  });

  return (
    bodies.find(({ body }) => Object.keys(body).length) || {
      body: {},
      type: null,
    }
  );
};

test({firstKey: '123'}, ['firstKey']);

Upvotes: 0

Views: 192

Answers (3)

ghostagent151
ghostagent151

Reputation: 1406

This can be closed, its actually my fault, I mistakenly passed in an array for the 2nd argument of the function call, where it should be an object. Also, includes should've been called on whitelist and not whitelists.

In actuality it looks like test({firstKey:'123'}, {whitelist: ['firstKey']})

Upvotes: 0

Evgeny Yudin
Evgeny Yudin

Reputation: 143

1) set default = []

  const bodies = whitelists.map(({ type = null, whitelist = [] }) => {

or

2) replaced whitelist to whitelists

if (whitelists.includes(key)) {

Upvotes: 1

Guerric P
Guerric P

Reputation: 31815

That's because you are passing an array as second parameter of test, then you try to extract a whitelist property from this array, which makes no sense.

The console.log('whitelist ', whitelist) shows undefined as expected, because ['firstKey'].whitelist is undefined.

Not sure what you are trying to do here.

Upvotes: 1

Related Questions