Home > Software engineering >  checking if an object contains any values besides expected ones
checking if an object contains any values besides expected ones

Time:07-15

I want to check if an object has a value besides pageSize & pageStart & page , these values arent always all there for example sometimes pagestart will be missing if it equals 0. So checking the length of the object isnt reliable.

let object = { pageStart: 50, page: 2 userName: "Bobby" }

I want to check if the object contains anything besides these values and return a true/false.

CodePudding user response:

One concise option would be to destructure those properties out, use rest syntax to put the rest of the properties into their own object, then see if that object contains any properties.

const { pageSize, pageStart, page, ...rest } = object;
return Object.keys(rest).length >= 1;

CodePudding user response:

You can use some() testing if any of the Object.keys are not included in an array of expected keys. Here using Set.has() for efficient repeat polling. some() will short-circuit on the first match.

const hasUnexpectedKeys = (obj, expected) => {
  const expectedSet = new Set(expected);
  return Object.keys(obj).some(k => !expectedSet.has(k));
}

const expected = ['pageSize', 'pageStart', 'page'];

console.log(
  hasUnexpectedKeys({ pageStart: 50, page: 2, userName: "Bobby" }, expected)
); // true

console.log(
  hasUnexpectedKeys({ pageSize: 4, pageStart: 50, page: 2 }, expected)
); // false

Alternatively with just Array.includes()

const
  expected = ['pageSize', 'pageStart', 'page'],
  object = { pageStart: 50, page: 2, userName: "Bobby" };

console.log(
  Object.keys(object).some(k => !expected.includes(k))
);

CodePudding user response:

Iterate all keys of object (or some) and if you find something not in the whitelist, then raise a flag.

var allowed = "pageStart,page,userName".split(",")
var obj1 = {
  page: 2,
  pageStart: 2,
  hello: 'world'
}
var obj2 = {
  page: 2,
  pageStart: 2
}

function find_alien(obj) {
  for (var key in obj) {
    if (allowed.indexOf(key) === -1) {
      return key;
    }
  }
  return false;
}

console.log(find_alien(obj1))
console.log(find_alien(obj2))

  • Related