Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Is it possible to display substring from object entries in JavaScript?
Yes, you can display substrings from object entries in JavaScript using Object.fromEntries() combined with string methods like substr() or substring(). This technique allows you to transform object keys while preserving their associated values.
Syntax
Object.fromEntries(
Object.entries(object).map(([key, value]) =>
[key.substr(startIndex, length), value]
)
)
Example: Extracting Substring from Object Keys
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);
{ 'John 21': 1010, 'John 24': 1011, 'John 22': 1012, 'John 22': 1013 }
Using substring() Method
You can also use substring() method for more flexible string extraction:
const data = {
"Product_ABC_2024": 500,
"Product_XYZ_2023": 750,
"Product_DEF_2022": 300
};
// Extract only the product code (middle part)
const extractedCodes = Object.fromEntries(
Object.entries(data).map(([key, value]) => {
const parts = key.split('_');
return [parts[1], value]; // Get middle part
})
);
console.log(extractedCodes);
{ ABC: 500, XYZ: 750, DEF: 300 }
How It Works
The process involves three steps:
-
Object.entries()converts the object to an array of [key, value] pairs -
map()transforms each key using string methods likesubstr() -
Object.fromEntries()converts the transformed array back to an object
Conclusion
Using Object.fromEntries() with string methods provides a powerful way to transform object keys while maintaining their values. This approach is useful for data cleaning and key normalization tasks.
Advertisements
