Syntax, Parameter and Return Value
Syntax:
_.fromPairs(pairs)
Parameters:
pairs (Array): The array of key-value pairs.
Return Value:
(Object) - Returns the new object.
Examples
Converting Simple Pairs:
var _ = require('lodash');
var pairs = [['a', 1], ['b', 2]];
var object = _.fromPairs(pairs);
console.log(object);
Output:
{ 'a': 1, 'b': 2 }
This basic example demonstrates converting an array of pairs into an object.
Handling Pairs with Mixed Types:
var mixedPairs = [['id', 1], ['name', 'Alice'], ['active', true]];
var mixedObject = _.fromPairs(mixedPairs);
console.log(mixedObject);
Output:
{ 'id': 1, 'name': 'Alice', 'active': true }
Here, _.fromPairs() is used to create an object from pairs with different data types.
Converting Query String Parameters:
var queryString = [['page', '1'], ['sort', 'name'], ['order', 'asc']];
var queryObject = _.fromPairs(queryString);
console.log(queryObject);
Output:
{ 'page': '1', 'sort': 'name', 'order': 'asc' }
An example showcasing the conversion of query parameters into an object.
Transforming CSV Data:
var csvData = [['name', 'John'], ['age', '30'], ['country', 'USA']];
var csvObject = _.fromPairs(csvData);
console.log(csvObject);
Output:
{ 'name': 'John', 'age': '30', 'country': 'USA' }
Demonstrates how to turn CSV-like data into a structured object.
Frequently Asked Questions
Can _.fromPairs() handle more complex structures within pairs?
Yes, it can handle pairs with complex structures, including nested arrays and objects, effectively turning them into an object with corresponding keys and values.
What if a key appears more than once in the pairs array?
If a key is repeated in the pairs, _.fromPairs() will use the value from the last occurrence of that key.
How does _.fromPairs() benefit data manipulation in JavaScript?
_.fromPairs() simplifies data transformation, allowing for more intuitive and accessible object-based data manipulation compared to array-based handling.
Conclusion
The Lodash _.fromPairs() method serves as a bridge between array representations and object structures in JavaScript. Its ability to transform key-value pair arrays into objects is pivotal in data processing, enhancing the readability and manageability of data. This function is a testament to the flexibility and efficiency offered by Lodash in JavaScript data manipulation.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.