0

I want to create a property on an object conditionally. The idea is to ensure the property doesn't exist (so not just null) if it has no value.

What I'm doing right now:

// comes from users
req.query = {
  foo: true
}

// my object which will contains allowed properties IF EXISTS
const where = {}

if (req.query.foo) {
  where.foo = req.query.foo
}
if (req.query.bar) {
  where.bar = req.query.bar
}

console.log(where)

It's really boring to repeat this for every different property...

Is there a way to do it in one line?

EDIT:

I don't want to get all properties from req.query

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
mbesson
  • 629
  • 5
  • 24

6 Answers6

9

Create object property obj.foo if value exists (or any other condition)

&& operator returns second element if the first boolean condition is fulfilled

es6 spread operator ... does what it does)

const value = 'bar'

const empty = undefined

const obj = {
  ...value && { foo: value }, // read ...(value && { foo: value }) parenthesis are not necessary
  ...empty && { empty },
  ...(100 > 0) && { condition: 'true' },
  ...(100 < 0) && { condition: 'false' },
}

console.log(obj)
mbesson
  • 629
  • 5
  • 24
Nikita Mazur
  • 1,602
  • 1
  • 5
  • 14
0

You could do:

const merged = {...where, ...req.query};
Gpack
  • 1,878
  • 3
  • 18
  • 45
0

Try this:

const elements = ["foo", "bar"];

elements.forEach(el => {
    if (req.query[el]) {
        where[el] = req.query[el];
    }
});
moustafa
  • 251
  • 2
  • 11
0

You can simply write it in one line like this :

let where = {};
if (req.query.foo) where = {...where, foo : req.query.foo };
if (req.query.bar) where = {...where, bar : req.query.bar };

I hope that it helps.

Mohamed Ayadi
  • 83
  • 1
  • 8
0

If you want a simple one liner (maybe less readable), you can do:

Object.keys(req.query).forEach(key => req.query[key] && (where[key] = req.query[key]));
Yoni A
  • 124
  • 8
0

If you're okay adding a pluck function, you could do it like this:

const req = { query: { baz: '1', foo: '3' } };
const where = {};

const pluck = (keys, obj) =>
  keys.reduce((a, k) => typeof obj[k] === 'undefined' ? a : Object.assign(a, { [k]: obj[k] }), {});

const add_foo_bar = (where, query) =>
  Object.assign({}, where, pluck(['foo', 'bar'], query));

const res = add_foo_bar(where, req.query);

console.log(res);
Ben Stephens
  • 3,303
  • 1
  • 4
  • 8
  • I think this is the cleaner solution but I was searching for a solution without adding a function – mbesson Jun 08 '21 at 11:44