Henok Tesfaye
Henok Tesfaye

Reputation: 9580

Perform operation on destructured element in JS object

function capitalizeFirstLetter (string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

I want to capitalize the title after destructuring in one line,

const { question } = this.props
const {
  title,
  Question_uuid: questionUUID
} = question

How to capitalize property title after destructuring. ":" renames the variable and "=" assigns a default value.

Upvotes: 2

Views: 424

Answers (2)

adiga
adiga

Reputation: 35259

Destructuring is just a way to unpack values from objects and arrays. You cannot perform any action on the destructured values. You'd have to to do that in a separate line:

let { title } = question;
title = capitalizeFirstLetter(title)

There are some hacks to make it happen while destructuring. (These are purely academic and should not be used in an actual code base)

One option is to create another variable and assign a default value

const { title, updatedTitle = capitalizeFirstLetter(title) } = question 

This translates to

var title = question.title,
    updatedTitle = question.updatedTitle === undefined 
                    ? capitalizeFirstLetter(title) 
                    : question.updatedTitle;

As you can see, this only works if the newly created variable name updatedTitle doesn't exist in question as a key.


There is another way to create a title variable without creating an extra variable. You could create a getter in String.prototype called capitalize. Destructure the title property from question to get the capitalize property

Object.defineProperty(String.prototype, "capitalize", {
  get: function() {
    return this.charAt(0).toUpperCase() + this.slice(1)
  }
});

const question = { title: 'lower case question' }
const { title: { capitalize: title } } = question

console.log(title)

This translates to:

const title = question.title.capitalize;

The getter in String.prototype will be called and it will assign the capitalized string to the title variable.

Upvotes: 2

Will Jenkins
Will Jenkins

Reputation: 9907

As far as I know you can't change the original property but you can do this:

const {
  title,
  titleCap = capitalizeFirstLetter(title)
} = question

i.e. declare a 'dummy' variable that you provide a default value for. This would be a bad idea though - if at some point the value ever did exist in the original prop then your default value would be ignored.

Upvotes: 1

Related Questions