JavaScript: Return the object associating the properties to the values of a given array of valid property identifiers and an array of values
JavaScript fundamental (ES6 Syntax): Exercise-101 with Solution
Write a JavaScript program to return the object associating the properties to the values of a given array of valid property identifiers and an array of values.
Note: Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using Array.reduce().
Associates properties to values, given array of valid property identifiers and an array of values.
- Use Array.prototype.reduce() to build an object from the two arrays.
- If the length of props is longer than values, remaining keys will be undefined.
- If the length of values is longer than props, remaining values will be ignored.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const zipObject = (props, values) =>
props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});
console.log(zipObject(['a', 'b', 'c'], [1, 2]));
console.log(zipObject(['a', 'b'], [1, 2, 3]));
Sample Output:
{"a":1,"b":2} {"a":1,"b":2}
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-101-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to create an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.
Next: Write a JavaScript program to create an array of elements, grouped based on the position in the original arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join