Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the casing title of the object inside an array

An array contains objects with property "title" which contains lower-casing text with _ . Need to change the title by splitting '_' and need to capitalize first letter after every space .

I can change all the title casing to upper case but I need only the first letter after space should be capitalized

  const listData = [
        {
            "title": "some_id",
            "dataTypes": "character varying(65535)"
        },
        {
            "title": "some_value",
            "dataTypes": "character varying(65535)"
        }
  ]
  const newData = []
  listData.map(el => newData.push({"title":el.title.toUpperCase().split('_').join(' '),"dataTypes" : el.dataTypes }))
  console.log(newData);

Expected :

   const newData = [
        {
            "title": "Some Id",
            "dataTypes": "character varying(65535)"
        },
        {
            "title": "Some Value",
            "dataTypes": "character varying(65535)"
        }
  ]

Actual :

  const newData = [ 
  { title: 'SOME ID' ,
   dataTypes: 'character varying(65535)' },
  { title: 'SOME VALUE' ,
   dataTypes: 'character varying(65535)' } ]
like image 902
RenJith Avatar asked Sep 06 '19 04:09

RenJith


People also ask

How do you change an object in an array?

To change the value of an object in an array:Call the findIndex() method to get the index of the specific object. Access the array at the index and change the property's value using dot notation. The value of the object in the array will get updated in place.

Can you use toUpperCase in an array?

To convert all array elements to uppercase: On each iteration, call the toUpperCase() method to convert the string to uppercase and return the result. The map method will return a new array with all strings converted to uppercase.

How do you change an object array to an array?

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() . Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.


1 Answers

You can do this:

const listData = [
  {
      "title": "some_id",
      "dataTypes": "character varying(65535)"
  },
  {
      "title": "some_value",
      "dataTypes": "character varying(65535)"
  }
]

const newData = []
listData.map(el => newData.push({
  "title":el.title.split('_').map( word => {
    return word[0].toUpperCase() + word.substring(1, word.length);
  }).join(' '),

  "dataTypes" : el.dataTypes }))
console.log(newData);

You will have to iterate through the split title and update the first letter.

The result is:

[ { title: 'Some Id', dataTypes: 'character varying(65535)' },
  { title: 'Some Value', dataTypes: 'character varying(65535)' } ]
like image 142
Lone Ranger Avatar answered Sep 30 '22 06:09

Lone Ranger