Is it possible to display substring from object entries in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Yes, you can use Object.fromEntries() along with substr(). Under substr(), mention the index from where to begin the substring and the length.

Example

const originalString = {
   "John 21 2010" :1010,
   "John 24 2012" :1011,
   "John 22 2014" :1012,
   "John 22 2016" :1013,
}
const result = Object.fromEntries(Object.entries(originalString).
map(([k, objectValue])=>
[k.substr(0, k.length-5), objectValue]));
console.log(result)

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo41.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo41.js
{ 'John 21': 1010, 'John 24': 1011, 'John 22': 1013 }
raja
Published on 01-Sep-2020 12:10:01
Advertisements