Develop a new entity utilizing Array in Javascript

let DaysArray: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

I am looking to transform the above array into an Object structure as shown below:

let DaysObject: any = {
    time: {
        headerName: ""
    },
    monday: {
        headerName: "Monday"
    },
    tuesday: {
        headerName: "Tuesday"
    },
    wednesday: {
        headerName: "Wednesday"
    },
    thursday: {
        headerName: "Thursday"
    },
    friday: {
        headerName: "Friday"
    },
    saturday: {
        headerName: "Saturday"
    },
    sunday: {
        headerName: "Sunday"
    }
};

Can anyone help me with writing a for loop in JavaScript to achieve this transformation? I appreciate any assistance, thank you!

Answer №1

Convert an array to an object in JavaScript using the reduce method: 

var result = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].reduce(function (acc, element) { 
     acc[element] = {};
     acc[element].headerName=element;
     return acc;
}, {time: ""});
console.log(result);

You can find more information about the reduce method on MDN.

Example of using reduce to convert an array to an object:

any.reduce(function (acc, element) { 
     acc[element] = {};
     acc[element].headerName=element;
     return acc;
}, {time: ""})

Answer №2

Here is a simple solution for you:

var daysOfWeek = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
var outputObj = { //initialize new object with default value
  time: {
    headerName: ""
  }
};
daysOfWeek.forEach(function(day) { //loop through daysOfWeek array and add key-value pairs to the new object
  outputObj[day] = {
    headerName: capitalizeFirstLetter(day)
  };
});

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

console.log( outputObj );

Answer №3

var weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

var result = {};
result['time'] ={headername:""};
weekdays.map(function(day){
result[day] = {headername: day};

})
console.log(result)

Answer №4

Implementing a For loop.

function convertArrayToObject(arr) {
  var result = {};
  for (var index = 0; index < arr.length; ++index)
    if (arr[index] !== undefined) result[arr[index]] = {"name":arr[index]};
  console.log(result);
}
convertArrayToObject(["apple", "banana", "cherry", "date", "elderberry"]);

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

Encountered difficulty locating the module path 'stream/promises'

When importing the following in a typescript nodejs app import { pipeline } from "stream/promises"; Visual Studio Code (vscode) / eslint is showing an error message Unable to resolve path to module 'stream/promises' This issue appeare ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

Verify if the currentRoute begins with a specific text pattern (such as something/something/*...) in Angular

I need to prevent a loader from appearing on certain screens, so I used ngIf on routes where the loader is not necessary. Here's the code snippet from app.component.ts : <router-outlet> <app-spinner></app-spinner> <ngx-ui-load ...

Why does parsing the GET response fail intermittently with Jquery, ajax, and JSON?

Currently, I am encountering an issue with ajax calls using jQuery where the response being returned is a JSON array. In certain scenarios, everything works perfectly fine. However, in other cases specifically in browsers like Firefox and IE11, there seems ...

What is the best way to make a select tag read-only before the Ajax request is successful

Is there a way to make a select tag read-only before an Ajax success? I tried using this code, but it didn't work: $("#tower").prop('readonly', true); Then I tried this alternative, but I couldn't get the value from the select tag: ...

Images appear as plain text in the preview of VUE 3 (with TypeScript)

Currently, I am developing a Portfolio website and have encountered an issue. While everything runs smoothly with npm run dev, the problem arises when I use npm run preview. In this scenario, some of the images within the files named 3dModellingFiles.ts do ...

AngularJS provides a convenient way to manage content strings

As I embark on developing a large AngularJS application, I am faced with the need to manage UI text content. This is crucial as elements like contextual help will require post-launch editing by the client in response to user feedback. I am currently explo ...

Creating a nx workspace for vanilla JavaScript (Error: module 'typescript' not found) - Step-by-step guide

Looking to set up a new workspace for plain React applications. How can I do it? Create Workspace npx create-nx-workspace@latest # version 15.2.1 # style: package-based # distributed caching: NO Installing the react-package npm install -D @nrwl/react Cr ...

Applying conditional formatting to NumPy array elements

I am working with a 3D numpy array and need to change a specific element based on a conditional test of another element. In this case, I am adjusting the 'alpha' of a RGBA image array to manipulate transparency in a 3D pyqtgraph image, with a foc ...

A Node.js middleware that logs a message just once

My nodejs express app serves a file that requires and loads css files, js files, etc. I have implemented a logging middleware that retrieves the client's IP address and logs it (after cross-checking with a JSON file containing malicious IPs). Due to t ...

Unable to determine the data type of the JSON object during the

I'm having trouble reading an Object type of json... Here is the json I'm working with: body: { "111": { "name": "name1", "status": 10000 }, "222": { "name": "name2", "status": 20000 }, "333": ...

What is the reason for having to add my IP to the white-list daily?

As a beginner, I am delving into the world of back-end development with Node.js, Express.js, and Mongoose for educational purposes. My database is hosted on Atlas-Mongo DB. Initially, everything seemed to be running smoothly as I configured it with the fre ...

VueJS Error: Unable to access the 'className' property of an undefined variable

I'm currently working on a menu design project where I need to highlight the active tab/page that the user is on by adding a color class and utilizing JavaScript to update the active link. Here's a snippet of my template: <div class="menu ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

The functionality of allowEmpty : true in gulp 4.0 does not seem to be effective when dealing with

gulp.task("f1", () => { gulp.src([], {"allowEmpty": true}) .pipe(gulp.dest(location)); }) An error message pops up saying "Invalid glob argument:" when the code above is used. gulp.task("f1", () => { gulp.sr ...

What is the best way to merge multiple chunks of arrays into a single array

What I currently possess: let json = { key1: 'value1', key2: 'value2', key3: { title: 'yeah' } } let path = ['key3', 'title']; My goal is to concatenate segments of the 'path' array ...

Sharing environment variables in gulpfile with other JavaScript files outside NODE_ENV

Is it possible to pass a variable other than NODE_ENV from the gulpfile.js to another javascript file? gulpfile.js // Not related to NODE_ENV! let isDevelopment = true; somejsfile.js /* I need to access "isDevelopment" from the gulpfile.js... For the ...

jQuery's Multi-Category Filter feature allows users to filter content

I have been working on creating a filter function for my product list. The idea is that when one or more attributes are selected, it should fade out the elements that do not match. And then, if a filter is removed, those faded-out items should fade back in ...

modifying input field with radio button selection in Jquery

Is there a way to set the input field to have a default value and then change it, or disable it with a different value? $("#tax").value(19).prop("disabled",false); $("#tax").value(0).prop("disabled",true); <script src="https://ajax.googleapis.com/aj ...

What is preventing me from obtaining the select and input values?

I'm currently facing an issue where I am unable to retrieve the values of customInput and customSelect and store them in the state. The challenge arises when trying to integrate these components into a react dashboard material-ui setup. Strangely, whe ...