Naming JavaScript properties based on array values

Can array values be transformed into property names for an object in a single line?

For example:

var arr = ['name', 'age', 'size'];

To achieve:

{'name' :null, 'age':null, 'size':null}

Currently, the process involves:

var arr = ['name', 'age', 'size'];
let obj = {};
arr.map(z => obj[z] = null);

This method seems to be the shortest but certainty is in question.

Answer №1

Implement the use of reduce:

arr.reduce((prev, curr) => {
  return Object.assign(prev, {[curr]: null})
}, {})

Alternatively, you can condense it into a single line if desired, but personally, I find it less readable than:

arr.reduce((prev, curr) => Object.assign(prev, {[curr]: null}), {})

Keep in mind that utilizing Object.assign is a more optimal approach compared to employing the spread operator ({... }).

The spread operator generates a NEW object in each iteration, potentially causing significant performance drawbacks.

On the contrary, Object.assign operates on the initial object.

Answer №2

Transform can simplify this to a single line of code:

let result = array.reduce((accumulator, current) => ({...accumulator, [current]: null}), {})

Answer №3

To transform an array into a different type, you can utilize the Array.prototype.reduce method.

var fruits = ["apple", "banana", "orange"];

let output = fruits.reduce((result, item) => {
  return {...result, [item]: null}
}, {})

console.log(output);

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

Enable the button when there is an error after submission in AngularJS

Has anyone encountered issues with dynamically disabling a button? I noticed that my API delays for 2 seconds to mimic a slow connection. I expected the submit button to be disabled upon submission and then re-enable itself. In HTML, manually disabling t ...

Manipulate the visibility of a child element's dom-if based on a property retrieved from the parent element

Exploring the world of Polymer, I am eager to tackle the following scenario... I have a binding variable called {{readonly}} that sends data from a parent Dom-HTML to a child Dom-HTML in my Polymer project. The code excerpt looks something like this... C ...

Manipulating the contents of a C++ C-style string by deleting characters

I have a .txt file with the following content... City- Paris Colour- Blue Food- Croissant Language- French Rating- 5 stars I am trying to separate the text before the hyphen or whitespace into one array and the text after into another array. My current ...

Incorporating a CSS drop-down menu that appears or changes upon clicking

I am in the midst of designing a webpage with a main div that is 1000px by 1000px. Within this main div, there is a horizontal bar located at the top, divided into four sections - each occupying 1/4 of the space. In the center of each section, there is tex ...

rotation of a Object3D in three.js

I am a beginner in using three.js and have encountered an issue with rotating a camera object. The rotation property has x, y, z values which I am curious about. I understand that the x, y, z values represent the radians of Object Euler angles, but accor ...

The issue is that AngularJS deferred.reject function is not functioning properly, while the $q

I'm struggling to understand the difference between Angular JS deferred and $q. I recently came across this SO Question that delves into the variance between $q.defer() and $q. According to the post: $q.reject serves as a quick way to create a defe ...

What is the best approach for Angular directives: utilizing a single object or separate values as attributes?

This question pertains to best practices, but I do believe there is a definitive answer. I have a directive that offers six customizable options. Should I assign each option to a separate attribute on the directive (as shown below): <my-directive my ...

Partially extended texture in Three.js

Currently, I am using the Collada loader in Three.js r65 to load my 3D object. Upon loading, I apply a texture to all parts of the model using the following code snippet. var loader = new THREE.ColladaLoader(); loader.options.convertUpAxis = true; loader ...

Guide on uploading multipart career-form data with file paths and validation in CodeIgniter with the help of AJAX

I am facing an issue while attempting to insert job form data with file uploading and validation in PHP CodeIgniter via AJAX. The code I am using is provided below, but unfortunately, it's not functioning as expected. Can anyone help me figure out how ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Knockout Js' observable objects are not updating the UI to reflect changes in the data

Displayed below is the view modal where an ajax response is obtained and loaded into the observable value. var userManagementVM = { responseSetUpData: ko.observable({ userList: ko.observable(), userListViewModel: ko.observableArray(), ...

Mongoose: Issue with validation not triggering upon save action

In my Mongoose schema, I have defined the following: // validator function var validateArrayWithAtLeastFiveElements = function (array) { return (array !== undefined && array.length >= 5); }; var orderSchema = new Schema({ user: { ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty(): class User { private name: string; private age: number; constructor(data: JSON) { ...

What is the best way to remove words from an object's value that begin with a specific keyword using JavaScript?

Here is a sample array. I need to remove the words row-? from the className property. [ { type: "text", name: "text-1632646960432-0", satir: "1", className: "form-control col-lg-3 row-1" }, { ...

Exploring the dynamic JSON object from D3 in a Rails view

Currently, I am in the process of learning D3 and my initial attempt involves showcasing a graph where I manually hard-code the json data. To demonstrate this, I have put together a JSFiddle which you can view here: http://jsfiddle.net/Nu95q/1/ The JSFid ...

Find the location of $value in MongoDB where the timestamp is greater than or equal to JS

When attempting to find a nested element's existence and get a timestamp greater than a certain value, I'm encountering an issue: db.stats.find( { $and: [ { 'data.Statistics': {$exists: true} },{ timestamp: {$gte: 1} } ] } Although ...

the event listener for xmlhttprequest on load is not functioning as expected

I am facing an issue with validating a form using JavaScript and XMLHttpRequest. The onload function is supposed to display an alert, but it only works sometimes. I'm struggling to identify my mistake. document.getElementById("button").addEventListen ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...