LearnFrenzy
Sign in Take a free test

Array Methods · Array Methods Coding Problems · Question 7

Zip two arrays into an object in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
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
main.js
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);

Output Verified by running it on Node.js

{ 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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links