-1

I have a simple arrow function:

const db = (url, type, body?) => ({url, type, body})

and I don't want to return body property if it's an empty db argument.

4
  • Explain question properly with more details Commented Feb 3, 2020 at 10:31
  • just write an if condition Commented Feb 3, 2020 at 10:32
  • 1
    By "empty", you mean undefined? That's exactly what body should become when you want to "omit" it - your code already works! Commented Feb 3, 2020 at 10:33
  • No, because then there is an entry body: undefined in the resulting object. Furthermore, the question mark after body is not working in a browser Commented Feb 3, 2020 at 10:38

3 Answers 3

2

Ask for the value of body

const db = (url, type, body) => Object.assign({url, type}, (body ? {body} : {}));
console.log(db("Ele", "Stack"));
console.log(db("Ele", "Stack", "mybody"));

Sign up to request clarification or add additional context in comments.

Comments

1

You can do:

const db = (url, type, body) => (body ? {url, type, body} : {url, type})

4 Comments

OP didin't give details about the body parameter but i guess it's an object. So you must check the length with Object.keys()
@MaximeGirou An empty object is different from "no object" already, you don't need to count its properties for that.
It can be anything, it doesn't matter too much. The OP mentioned that if it was not provided, it shouldn't be returned. It it is not provided, body will be undefined and the correct object will be returned. It is true however, that false or an empty body object would return the short object as well
it depends on what the OP means when he says 'empty'. if it is an empty object or undefined
0

You can check this way

const db = (url, type, body) => (Object.keys(body).length > 0 ? { url, type, body } : { url, type })

1 Comment

Nobody said body needed to be an object. If it is not passed to the function, a simple undefined check is enough

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.