What is best approach in extracting the below object. I tried two ways. Can this be refactored in any other way to optimize the performance?
const data = {
"postcode": [
"123456"
],
"time": [
"05:11"
]
};
Approach 1:
for (const element of Object.entries(data)) {
const key = element[0];
const value = element[1][0];
data[key] = value;
}
Approach 2:
for (const key in data) {
if (Object.hasOwnProperty.call(data, key)) {
data[key] = data[key][0];
}
}
console.log('data ', data);
Object.fromEntries()and.map()to make your code more concise, but if you're after performance improvements I don't think much can be done, other than some potential micro-optimizations that won't make much of a difference in the grand scheme of things.const res = Object.fromEntries(Object.entries(data).map(([key, [val]]) => [key, val]));, adding this as a comment as this doesn't answer your question of optimizing your code (it would make your code slightly slower actually), it's just more concise I guessfor (const key in data) {would be the most efficient (assuming the prototype isn't filled with enumerable properties), as it is only one iteration of the object, whereas.entries()+for..ofleads to two iterations over the keys/values.