Question 7
Back to Exercise
Combine a header row and a data row (from a CSV file) into an object, and convert numeric fields to numbers.
Solution
const headers = ["name", "age", "city", "score"];
const row = ["Asha", "21", "Pune", "88.5"];
const record = Object.fromEntries(
headers.map((h, i) => {
const value = row[i];
return [h, value !== "" && !isNaN(value) ? Number(value) : value];
}),
);
console.log(record);
console.log(typeof record.age, record.score + 1.5);
{ name: 'Asha', age: 21, city: 'Pune', score: 88.5 }
number 90
map uses the index to pair each header with the value at the same position, and Object.fromEntries turns the pairs into an object.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!