Is there a way to use lodash to convert an array into an object?

Below is an array that I am working with:

const arr = [ 'type=A', 'day=45' ];
const trans = { 'type': 'A', 'day': 45 }

I would appreciate it if you could suggest the simplest and most efficient method to achieve this. Thank you!

Answer №1

To verify if the string can be split and determine whether the value is isNaN, you can either convert it to a numerical value.

var data = [ 'type=A', 'day=45', 'bar=0' ],
    obj = Object.create(null);

data.forEach(function (item) {
    var part = item.split('=');
    obj[part[0]] = isNaN(part[1]) ? part[1] : +part[1];
});

console.log(obj);

Answer №2

One way to solve this is by utilizing the Array.prototype.reduce() function:

const inputArray = [ 'type=A', 'day=45' ],
    transformedObject = inputArray.reduce(function(result, item){
        let parts = item.split('=');
        result[parts[0]] = isNaN(parts[1]) ? parts[1] : +parts[1];
        return result;
    }, {});

console.log(transformedObject);

Answer №3

  1. Go through each element in the array
  2. Divide using =
  3. Include the value into object, under specified key

var arr = [ 'type=A', 'day=45' ];
var object = {};

for (var i = 0; i < arr.length; i++) {
  var currentItem = arr[i].split('=');
  var key = currentItem[0];
  var value = currentItem[1];
  object[key] = value;
}

console.log(object);

Answer №4

There are countless ways to achieve this task, and the method demonstrated here utilizes two distinct functions. The _.map() function iterates over each element in the array, splitting and parsing the element based on a character regex pattern. It then employs Lodash's .fromPairs function to convert an array comprised of 2-element arrays into an object.

var arr = ['type=A', 'day=45'];
var obj = _.fromPairs(_.map(arr, function(item) {
  var parts = item.split('=');
  var digits = /^\d+$/;
  if (digits.test(parts[1])) parts[1] = parseInt(parts[1]);
  return parts;
}));
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: The plugin 0 mentioned in the file "/my dir/node_modules/babel-preset-php/src/index.js" contains an invalid property called "default"

While attempting to convert a PHP script to JavaScript using babel-preset-php, I encountered the following error: Error: Plugin 0 specified in "/media/deep/5738c180-2397-451b-b0b5-df09b7ad951e1/deepx/Documents/TestingAll/node_modules/babel-preset-php/ ...

The property fails to reflect changes in state

I am currently developing an application that requires fetching data asynchronously and preserving the state in the parent component while also passing the data reference to children components. I encountered an issue where the props do not update when the ...

Mysterious error arises in Internet Explorer versions 7 and 8: An expected colon is missing

One of our websites is encountering a puzzling JS error in Internet Explorer. The console displays the following message: ':' expected javascript:false, Line 1 Character 24 When attempting to trace the source of the error, a notification appear ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

The paragraph text should dynamically update upon clicking a button based on JavaScript code, however, the text remains unchanged despite attempts to modify it

I recently started learning JavaScript and wanted to update the content of a paragraph when a button is clicked. However, I encountered an issue where this functionality doesn't seem to work. <body> <p id="paragraph">Change Text on cl ...

Utilizing dynamic components in React JS

I'm a beginner in React JS and I'm facing an issue where I'm trying to call a React component from an HTML string that is being generated by another JavaScript class. However, the component is not rendering on the screen. class Form extends ...

utilizing React.js, learn how to extract the most recent user input and store it within an array

My Input component generates input tags dynamically based on JSON data. I've implemented the onChange method in the input tag, which triggers a function called "handleChange" using contextAPI to record the values in another component. The issue aris ...

Is it possible to retrieve the BrowserWindow by its unique identifier in Electron?

Imagine if the following function is called multiple times to instantiate BrowserWindow, specifically 5 times. let mainWindow; function createWindow() { "use strict"; mainWindow = new BrowserWindow({ height: height, width: width ...

What is the solution to fixing the JSON parsing error that says 'JSON.parse: bad control character in string literal'?

When sending data from NodeJS Backend to the client, I utilize the following code: res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) )) //No errors occur here and the object is successfully stri ...

Tips for effectively utilizing v-model and v-select in a dynamic manner

Is it possible to have a group of select elements in Vue.js that work independently with v-model without needing separate data properties for each one? For example, select 1 and select 2 should be treated as one group, while select 3 and select 4 are anot ...

Vue router is unable to render or mount the component at the root path

I am currently working on a webpage using vue, vue-router, and laravel. I have encountered an issue where the Home component is not being rendered in the router-view when I access localhost/myproject/public_html/. However, if I click on the router link to ...

After developing a React application to fetch data from my own API, I encountered the following error message: "TypeError: video.map is not a function". See the code snippet below:

import React, {useEffect, useState} from "react"; import Axios from "axios"; const VideoPage = () => { const [video, setVideo] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchVideoData = async() =&g ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

Using JavaScript to display a selection of objects from an array: showcasing x out of x items

What is the most efficient method for sorting or querying an array of objects using JavaScript? For example, how can I retrieve only the first two objects, followed by the next two, or obtain 5 objects starting from the 5th position? Which specific functi ...

What is the best way to display div elements based on a selected option?

Here is the code for a select list that contains the number of guests for a room: <select name="txtHotelGuestNO" id="txtHotelGuestNO" class="hotels" onchange="show_room_choose()"> <?php for($i=1;$i<=100;$i++) echo "<option value=$i>$ ...

Using AJAX to update the value of a div by clicking within a PHP loop

I'm currently working on a php page where I want to dynamically change the content of a div when a specific link is clicked. The links are generated through a loop, and I need to pass multiple parameters via the URL. Since the divs are also created wi ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

Stop ajax request when select2 is clicked

Is there a way to change the ajax call behavior in select2 drop down items so that it only retrieves data when I start typing in the search box, and not on click of the element? Your guidance on this issue would be highly appreciated. $("#ddlItems").sel ...

An element generated through JavaScript fails to display on the webpage

As I navigate through the code with a foreach() loop, my goal is to generate a new div every time a firebase document containing the user's email is encountered. The script involves a blend of react js and javascript as I am still learning the ropes o ...