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!
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!
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);
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);
=
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);
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>
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/ ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...
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 ...
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 ...
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>$ ...
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 ...
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[ ...
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 ...
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 ...