0

I'm trying to pretty much make my code clean and pretty.

I have something like this

let {name, city, address} = param.allParams()
let attr = {}

if (name) {

  attr.name = name
}

I wanted to see how I can condense even more. I tried this for example:

let {name, city, address} params.allParams()
let attr = {
  ... name,
  ... city, 
  ... address
}

I'm not sure I know what I was doing with the above example, but I'm experimenting and exploring javascript as well. Is there a better method to this?

thanks.

update: solution based on @Pointy comments

async update(req, res) {

    try {

      const results = await Company.update({id: req.params.id}, req.allParams())

      return res.ok(results)

    } catch (e) {

      return res.serverError(e)
    }
  }
Charlie
  • 22,886
  • 11
  • 59
  • 90
Eli
  • 4,329
  • 6
  • 53
  • 78
  • 2
    Those two pieces of code do significantly different things. What is it that you're trying to achieve? – Pointy Aug 17 '19 at 03:22
  • if a `param.name` is not undefined. to add it to the `attr` object – Eli Aug 17 '19 at 03:23
  • 1
    You don't have to extract the contents of `param` into separate variables if that's all you want to do. – Pointy Aug 17 '19 at 03:24
  • oh shoot, your right! – Eli Aug 17 '19 at 03:26
  • 1
    That solution looks like it might not be safe. Are there fields other than `name`/`city`/`address` that a user shouldn’t be able to update? Maybe that has the potential to update `id`? What’s the ORM? – Ry- Aug 17 '19 at 03:39
  • 1
    one possible way is instead of `... name,` use `... (name && {name}),` – guijob Aug 17 '19 at 03:46
  • Possible duplicate of [Remove blank attributes from an Object in Javascript](https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript) – Charlie Aug 17 '19 at 03:59
  • im using sails.js – Eli Aug 17 '19 at 12:10

1 Answers1

0

Unless param.allParams() is not something you control, you should not add undefined properties to your returning object.


If the shortest is what you are looking for, JSON.stringify removes undefined properties.

attr = JSON.parse(JSON.stringify(param.allParams()))

Also, this is the cleanest method:

var params = param.allParams();

Object.keys(params).forEach((key) => (params[key] === null) && delete params[key]);
Eli
  • 4,329
  • 6
  • 53
  • 78
Charlie
  • 22,886
  • 11
  • 59
  • 90