Utilizing ES6 array destructuring to directly assign values to an object without relying on functions

Is it feasible to achieve the following functionality without utilizing a map, reduce, or any other functions?

const arr1 = ['str', 'str2'];
let obj = {};
Object.assign(obj, [...arr1] : 'Value');
console.log(obj); // Anticipated result: { str1: 'Value', str2: 'Value' }

The objective is to transform each element of an array into an object key and assign it a fixed value. The syntax in question involves potential destructuring similar to the provided pseudo code. I am curious if this can be accomplished using a simple approach without additional functions. With no available information on this method, my curiosity led me to seek clarification on this matter.

Answer №1

You can't simply use the array elements as property names for separate properties in an object.

An easy way to achieve this is by using a loop after creating the object:

let obj = {};
for (const str of arr1) {
    obj[str] = 'Value';
}

Here's a live example:

const arr1 = ['str', 'str2'];
let obj = {};
for (const str of arr1) {
    obj[str] = 'Value';
}
console.log(obj); // Expected output: { str1: 'Value', str2: 'Value' }


If you want to get fancy, you can utilize Object.assign, temporary objects, spread notation, map, and an arrow function like this:

let obj = {};
Object.assign(obj, ...arr1.map(str => ({[str]: 'Value'})));

You can also check out Jared Smith's solution using fromEntries for another efficient approach similar to using assign.

Another option is to use reduce:

let obj = arr1.reduce((o, str) => {
    o[str] = 'Value';
    return o;
}, {});

Or you could condense it even further with the comma operator:

let obj = arr1.reduce((o, str) => (o[str] = 'Value', o), {});

In my opinion, keeping it simple with a loop is usually the best option. :-)

Answer №2

If you're interested, you have the option to utilize the latest feature called Object.fromEntries:

var obj = Object.fromEntries(arr.map(str => [str, "Value"]));

It's important to note that this functionality is relatively new and may require a polyfill in certain situations.

Answer №3

Spreading a value to create an object with the item as a key and another value is not achievable.

In order to generate an object with specific properties, you can modify the array by adding a custom generator function that returns an object for each item.

const arr1 = ['str', 'str2'];

arr1[Symbol.iterator] = function* () {
    for (let i = 0; i < this.length; i++) yield { [this[i]]: 'Value' };
};

let obj = {};

Object.assign(obj, ...arr1);

console.log(obj);

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

Limiting the values of JSON data in C3 charts

In my project, I have implemented c3 charts for creating dynamic charts. I am looking to only display the bars for values greater than 0. You can view the working example on this fiddle link. Specifically, I want to show the bars starting from the year 20 ...

What could be the reason behind the improper display of JavaScript for ID overlay2?

Why is it that when I try to have two overlays with different messages display upon clicking buttons, they both end up showing the same message? Even after changing the ID tag names, the issue persists. Can someone shed some light on what might be causin ...

Using JavaScript or jQuery to modify the URL of a webpage

Here is the HTML code I am working with: <form id="search-new"> <input type="text" name="search" placeholder="Search on the Site" value=""> <input id="search-submit" type="button" value="&rsaquo;"> </fo ...

Angular JS Promise - Implementing data binding within a forEach iteration

Currently, I am utilizing the angular.forEach function to loop through an array. For each value in the array, I am performing a GET request to fetch its corresponding name (the array includes keys), and then adding that name to another array. This new arra ...

What causes the failure of Angular 2 RC.6 routing when bundled with ngc + Rollup?

I have been exploring the new AOT Compiling feature in RC.6, but I have encountered a stumbling block. While I can successfully create a bundle using ngc => Rollup => Babel, I keep getting multiple warnings every time I run Rollup: The 'this&ap ...

Steps for exporting a module from a JavaScript file that is linked:

When I include the main.js file in my project, the code below works properly: modules.exports = { property: value } However, if I include it in a web page like this: <!DOCTYPE html> <html> <head> <script src="main.js"& ...

Transmit JSON data through a REST API request body

Looking to send a JSON request via REST, with client code in Node.js and server code in Golang. The structure of the body is as follows: const query = "{\"query\":\"query {n result: application(id: \"fb7b5992-4d0a-4782-acb7-13ae6cc66 ...

Modify the templateUrl in routeProvider according to the user's authorization

Is there a way to dynamically change the templateUrl in the router provider based on user permissions? Here's an example of what I'd like to achieve: $routeProvider .when('/',{ if(user) templateUrl:'app/views/pages/h ...

Having trouble with Ajax retrieving the updated JSON file version

I'm pretty new to coding and terminology in general, so I've done my best to simplify my code, although it might still have redundancies. Appreciate your patience in advance. My task involves using an ajax and php script to write data to a file ...

2020 Google Kickstart Challenge: Breaking Records with Incorrect Solutions

As I was practicing a problem from the last round of Google Kick Start 2020, I came across a challenging one called Record Breaker. The problem involves Isyana who is given the number of visitors at her local theme park on N consecutive days. A day is cons ...

Setting up KaTeX integration (code injection) on Circle.so

In my quest to create an online hub for IB Math students, I've decided to utilize Circle.so as my platform of choice. The diverse range of features offered by Circle.so, such as code injection capabilities and sleek design, make it an appealing option ...

Updating an ad unit dynamically in an HTML5 mobile web application through doubleclick DFP refreshing

I am currently working on developing an HTML5 mobile web application. The app loads, initializes, and constructs the user interface. Users can then pull in content through feeds, resulting in a dynamic display of changing content within the existing inter ...

Update the state of a button in an HTML header file

I am in the process of building a simple website, but it's starting to feel cluttered. One factor contributing to this clutter is that I have a separate header for each page since I don't have a script to dynamically change button states when hov ...

Separate the Array elements and organize them into an object

Check out this code snippet that demonstrates how to divide an array into chunks. If you have a more efficient solution, please share it with me. var numbers = []; for (var i = 0; i < 4500; i++) { numbers.push(i); } var chunks = {}; var start = 0 ...

Failure to prompt for authentication when accessing secure URLs via the $.ajax function

Whenever I work remotely, accessing URLs for our development servers always requires basic authentication. This means that every time a web page includes a script or link tag pointing to our development server, we encounter an authentication prompt. Recen ...

Using Fabric JS to update the image source of an element with a new URL

Can the src attribute of a fabric js object be changed to a CDN url? { version: '4.4.0', objects: [ { type: 'image', version: '4.4.0', originX: 'left', ... src:'www.cdn ...

Anticipate the completion of Subject callback execution

Take a look at the code snippet below: const mA = async () => { try { const subscription = myEmitter.subscribe(url => getD(url)); const la=()=>{...}; return la; } catch (error) { throw error; } }; ...

What is the best way to integrate Babel and React into my Express Application?

I must admit, I am a bit of a newbie when it comes to this, but I've been doing a lot of research trying to make this work with no luck so far. I enjoy working on my apps in Express and now I want to incorporate React for some of my reusable componen ...

Tips for personalizing an angular-powered kendo notification component by adding a close button and setting a timer for automatic hiding

I am looking to enhance the angular-based kendo notification element by adding an auto-hiding feature and a close button. Here is what I have attempted so far: app-custom-toast.ts: it's a generic toast component. import { ChangeDetectorRef, Componen ...

Any advice on applying jquery CSS to elements contained within a dynamically loaded div element?

element, I have encountered an issue with integrating a PHP file to process and display a table within a blank div element upon clicking a button. Despite applying styles from my style.css file, the jQuery mobile styles do not seem to be taking effect. I ...