w3resource

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
// Define the 'zipObject' function to create an object from arrays of properties and values.
const zipObject = (props, values) =>
  // Reduce the 'props' array to create an object by assigning each property to its corresponding value.
  props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});

// Test the 'zipObject' function with arrays of properties and values.
console.log(zipObject(['a', 'b', 'c'], [1, 2])); 
console.log(zipObject(['a', 'b'], [1, 2, 3]));

Output:

{"a":1,"b":2}
{"a":1,"b":2}

Visual Presentation:

JavaScript Fundamental: Return the object associating the properties to the values of a given array of valid property identifiers and an array of values.

Flowchart:

flowchart: Return the object associating the properties to the values of a given array of valid property identifiers and an array of values

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-101.php