Search code examples
javascriptnode.jsobjectecmascript-6destructuring

Capitalize values of destructed object


i have destructered req.body into:

const {
      logo = randomImg,
      category,
      name,
      owner,
      phone = "NA",
      location = "NA",
      website = "NA",
    } = req.body;

Now I want to capitalize name, owner.firstName, owner.lastname, and category. How can I do that?

i tried:

[category,name].forEach((s)=>{
  if (typeof s !== 'string') return ''
  return s.charAt(0).toUpperCase() + s.slice(1)
})

but this doesn't seem to change the actual value. Thanks in advance


Solution

  • You could take the wanted values and capitalize the strings and destruture the result to the given targets.

    [name, owner.firstName, owner.lastname] = [name, owner.firstName, owner.lastname]
        .map(s => typeof s === 'string'
            ? s[0].toUpperCase() + s.slice(1)
            : s
        );