Converting an array of strings into a keyed object in JavaScript using lodash: A step-by-step guide

If we have an array like this:

var arr = [ "one", "two", "three" ];

What is a more efficient method to convert it to:

{ "one": true, "two": true, "three": true }

I attempted the approach below, but I believe there could be a better solution.

 _.zipObject(arr || {}, _.fill([], true, 0, arr.length))

Answer №1

const newObj = array.reduce((o, value) => { return o[value] = true, o; }, {});

Answer №2

Implementing the code with Lodash:

const newArr = ['apple', 'banana', 'cherry'];

_.mapValues(_.keyBy(newArr), () => false);

Answer №3

Here is an easy solution for achieving the same result:

function convertToArrayToObject(array) {
   var obj = {};
   for (var j = 0; j < array.length; ++j)
   obj[j] = true;
   return obj;
}

Answer №4

let fruits = ["apple", "banana", "orange"];
let myMap = new Map();

for (let i = 0; i < fruits.length; i++) {
    myMap.set(fruits[i], true);
}

console.log(myMap);

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

Fetching server-side data for isomorphic React app: A guide to accessing cookies

Currently, I am in the process of developing an isomorphic/universal React + Redux + Express application. The method I use for server-side data fetching is quite standard: I identify the routes that match the URL, call the appropriate data-fetching functio ...

Exploring the organization of files: comparing the /bin and /dist directories

I often find myself confused when it comes to structuring my project directories in a way that is considered "professional." This confusion arises from the differentiation between the purpose of the 'bin', 'src', and 'build' d ...

Angular click directive

Exploring AngularJS and attempting to modify an example from a tutorial. I want the ng-init value to be equal to the value passed from a script function. How can I achieve this? Here's the code snippet: <html> <body> <h2> ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

Tips on utilizing a single modal to showcase various images

Based on the database table rows, my page will be populated with multiple rows (currently 32). Each row includes an image and a button/link at the end. I need a popup (#modal) to display the image fetched from the database when the button is clicked. I wa ...

Encountering an issue with Apollo Express GraphQL: Error message stating that the schema must have distinct type names, yet it contains more than one type named "DateTime"

After importing the applyMiddleware library from 'graphql-middleware' to add validation middleware on mutation's input, I created a sample middleware function that logs the input. export const logInput = async (resolve, root, args, context, ...

What causes the variable to be invisible in the imported file?

Within the main.js file, there is a specific code snippet: var test_mysql = require('./test_mysql.js') ... //additional code before(function(){ test_mysql.preparingDB(test_mysql.SQL_query.clear_data); // or test_mysql.preparingDB(SQL ...

Utilizing a JavaScript variable in a separate file: A guide

I am facing a JavaScript challenge where I have a variable that changes its value on a particular event. Now, I need to access this variable in a different file for some calculations. For instance, in my index.php file, I have the following variable: ...

Here is a unique version of the text: "Implementing a JavaScript function in Angular to activate the data-bs

Attempting to use JavaScript in angular to close/hide a bootstrap5 modal, encountering an issue where the hide function in bootstrap is not working. When manually clicking a button with data-bs-dismiss attribute, it closes the modal as expected, but when t ...

Guide to exporting everything within a div as a PDF using Angular 2

When attempting to convert a div with the id "div1" into a PDF using JSPdf in Angular 2, everything seems to be working fine until I try to export it to PDF. Here is my code snippet: <div class="container" id="div1"> <table> <tr> & ...

Use jQuery to swap out images and witness the image loading in real time

Currently, I am using jQuery to dynamically change images by using the code $('img').attr('src','newUrl'); However, whenever I do this, the image is only displayed once it has completely loaded. Due to my slow internet conne ...

Tips for identifying, initiating, and linking to the mobile version of Metamask through a button click on a web application, similar to the process on OpenSea

I recently integrated a shortcode into my project that leverages the Metamask browser extension to display the user's account using a combination of web3 and reactjs. The code functions flawlessly on desktop browsers, but encounters an issue when atte ...

How can I submit a form using ajax and retrieve the data as an array?

Hey there, I need some help on how to submit a form and receive data in the form of an array like this: { "notes":'some notes', "validUntil": '12/12/2015', "status": 1, "menuItemName": "HR Section", "menuItemDesc": "gggg" } Here is th ...

typescript - instantiate an object using values stored in an array

Assume we have a model defined as follows. export interface Basicdata { materialnumber: number; type: string; materialclass: string; } We also have an array containing values that correspond directly to the Basicdata model in order, like this: ...

The XML data does not provide any website addresses

After inputting all possible parameters and data into a URL, XML is not being returned. The locally hosted XML works fine, but not when using a URL. HTML: <section ng-controller="AppController" class="container-podcastapp"> <ul> ...

What is the best way to retrieve a particular nested value from a fetch POST response?

I performed a POST request in this manner: var myHeaders = new fetch.Headers(); raw = "srvrwd-ui=useMe" var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: &a ...

When working on a React/Redux application, how do you decide between explicitly passing down a prop or retrieving it from the global state using mapStateToProps?

As I embark on creating my inaugural React-Redux application, a recurring decision I face is whether to employ <PaginationBox perPage={perPage} /> or opt for <PaginationBox /> and then implement the following logic: function mapStateToProps({p ...

Storing a selected database column as a variable from an HTML page in Node.js with Express

My website showcases flight information pulled from a MySQL database. The process begins with a form where users select destinations and dates for their desired flight. Once the form is submitted, users are directed to another page where flights matching t ...

Using Javascript regular expressions to substitute $1 with the result of f($1)

I need to update a regular expression, let's say it looks like this: /url.com\/([A-Za-z]+)\.html/. My goal is to replace it with new string $1: f($1), which involves a constant string with two interpolations - the captured string and a funct ...

commenting system through ajax across multiple web pages

Experimenting with the webcodo comment system has led me to this URL: Database table: "comments" CREATE TABLE IF NOT EXISTS `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `email` varchar(60) NOT NULL, `comment` te ...