The most efficient method of assigning array indexes to boolean values within an object

Struggling to determine the most efficient method of assigning array indices to an object with boolean values. Currently employing the following approach:

let arr = [{t:1, te: "aa"}, {t:2, te: "aa"},{t:2, te: "aa"} ];
let obj = {}
arr.map((item, index) => (obj[index] = false));
console.log(obj)

If dealing with an array containing 200 objects, it would look like {0: false, 1:false, ....}

Considered using Array.reduce(), however unable to achieve desired result and consistently encountering:

var result = Object.assign(...arr.map(k => ({ [k]: true })));

{ 
   [object Object]: false
}

Is there a more concise way to accomplish this task in just one line?

Answer №1

To convert the objects into an array of entries with index-value pairs, you can then transform it into an object:

const objects = [{key:1, value: "apple"}, {key:2, value: "banana"},{key:3, value: "cherry"} ];
const newObj = Object.fromEntries(objects.map((_, index) => [index, false]));
console.log(newObj)

Answer №2

One way to utilize the index parameter is by using it in the callback function of the map method.

let arr = [{a: 1, b: "aa"}, {a: 2, b: "bb"},{a: 3, b: "cc"} ];
var obj = Object.assign(...arr.map((item, idx) => ({
  [idx]: true
})));
console.log(obj)

A similar approach can be taken using Array#reduce.

let arr = [{a: 1, b: "aa"}, {a: 2, b: "bb"},{a: 3, b: "cc"} ];
var obj = arr.reduce((acc, curr, index) => Object.assign(acc, {
  [index]: true
}), {});
console.log(obj)

Answer №3

const exampleList = [{type:1, text: "apple"}, {type:2, text: "banana"},{type:2, text: "orange"} ];
const result = exampleList.reduce((accumulator, object, index) =>  { return {...accumulator, [index] : false }}, {})
console.log(result)

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

Error: The current object referenced is not a constructor and has been invoked previously

I am facing an issue with my code involving an interpreter: //Interpreter.js class Interpreter { constructor() { this.data = "data"; } ... } module.exports = Interpreter; //index.js const Interpreter = require('./interpreter/I ...

Using Node.js to extract information from a web application that necessitates logging in

I find myself in a situation where I need to gather data from a webpage that does not have an API available. The scenario is as follows: In order to access the page data, one must first log in (usually resulting in the creation of session storage/cook ...

Tips for broadcasting the blob

I am currently working on a radio system project that involves streaming live audio from a microphone to the user in real-time. However, I am new to using node.js and unsure of how to achieve this. Can anyone provide guidance on how to stream the audio fro ...

Leveraging JavaScript within a Polymer component

I have an object made with polymer: <newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;"> <span class="title">Create a new folder</span> <input type="text" class="ginput" style="width: 350px; padd ...

Warning: Fastclick alerting about an ignored touchstart cancellation

Having an issue with a double popup situation where the second popup contains selectable fields. Below is the code snippet I am using to display the second popup: $("#select1").click(function(e) { e.stopPropagation(); var tmplData = { string:[& ...

Exceeded call stack size due to iterating through nested JSON structures

I'm currently working on a recursive function to navigate through a nested JSON structure. However, I've run into an error that says: Maximum call stack exceeded The function I've written looks like this: function createTreeMap (treeCat ...

Transitioning from JQuery to JavaScript with Carousel Bootstrap 5

I would like to implement a bootstrap 5 carousel that displays multiple items and slides one at a time. My goal is to convert the existing Jquery code into pure Javascript so that I can eliminate the dependency on Jquery. I came across this solution which ...

Include a class in the html root tag

Is there a way to dynamically add a class to the root HTML tag when a specific button is clicked? Most resources I've found only show how to add classes to div elements with IDs. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http ...

How can I adjust the border width of outlined buttons in material-ui?

Currently, I am in the process of modifying a user interface that utilizes Material-UI components. The task at hand involves increasing the thickness of the borders on certain outlined buttons. Is there a method through component props, themes, or styles t ...

Guide to implementing function callbacks in Nodejs using xml2js

In my Node.js project, I am utilizing xml2js to parse XML documents. Since the XML files I need are stored remotely, I make use of a Node.js http request to fetch the XML data and then perform parsing with xml2js in the following manner: var parser = new ...

Communication within the intermediate scopes between the directive and the controller

In my AngularJS HTML code, I have the following: <div ng-controller="myController"> <div ng-grid="myGrid"></div> </div> The ngGrid component creates a table-like structure with a viewport, rows, and cells, each having their ow ...

Form validation using JQuery within a Bootstrap 4 modal incorporating tabs is preventing submission

Encountering a challenge with JQuery Validation within a modal that contains tabs. When I'm on the Sign-in Tab and click the Login button, the validation errors display correctly: https://i.sstatic.net/caReK.jpg ISSUE 1 However, on the New Account ...

Utilizing XSLT 1.0 to Style JSON Results with XSLT/ Eliminating Default Quotation Marks in a JSON Array

After performing an XSLT transformation, I received a JSON response with the values in the "name" array needing to be displayed as "ABC","XYZ". Payload <Data> <Mapping> <LocationID>001</LocationID> <GeoX>1.00</GeoX ...

What is the method for obtaining the CSS text content from an external stylesheet?

I've spent countless hours trying to achieve the desired results, but unfortunately, I haven't been successful. Below is a summary of my efforts so far. Any helpful tips or suggestions would be greatly appreciated. Thank you in advance. Upon rec ...

Preventing Text Truncation in THREE.js Texture Created from 2D Canvas

Many people tend to use the 2D canvas texture method for creating text billboards, sprites, and overlays in THREE.js scenes instead of relying on imported image files. You can check out an example by Lee Stemkoski here. However, I have noticed that when a ...

When async is set to true in an Ajax call, the response may come

I recently developed a function that works perfectly fine when the async option is set to false. However, I am now looking to achieve the same functionality and return value but with async set to true. function Call(param, proc) { var url = "../../ ...

Breaking up an array with a designated value

Currently, I am dedicated to a project involving the development of a travel website. On the hotel page, the client has requested that hotels be listed according to their corresponding location. For example, places A and B have IDs 1 and 2, respectively. T ...

Regular expressions are compatible with JavaScript, but unfortunately, they are not supported

After successfully implementing this regex in my JavaScript for webpage validation, I attempted to incorporate it into my PHP script as a backup. However, every string I passed through the regex failed, even correct names. In an effort to resolve the issu ...

Is there a way to include a lockfile in a docker container as an optional step?

I am attempting to create a docker image that can optionally incorporate a yarn or npm lockfile during the build process. I want to include it explicitly, but also ensure that the build does not fail if the lockfile is missing. The goal is to respect dete ...

Update the three.js geometry when a user modifies the settings using dat.gui

I am currently working on updating a 3D spiral geometry in a canvas as the user adjusts a slider to change the number of coils. My approach involves using the dat.gui plugin for the interface. I have successfully implemented the slider to update an externa ...