What is the best way to transform the selected days of the week into comma-separated integers using JavaScript?

Users can select checkboxes for each day of the week.

Below is an example JS object:

{"mon":true,"tue":true,"wed":true,"thu":false,"fri":false,"sat":false,"sun":false}

The goal is to convert these selections into a string of comma-separated values, with Monday as 0 and so on. For example, if only Sunday is selected, the string would be

7

A conversion attempt has been made using the following code:

 var b = days;
 days = days.map(function (a) {
  return b.indexOf(a);
            });

Answer №1

Here is a method that utilizes a lookup table to convert days of the week into day numbers, collects the selected numbers in an array, and then converts the array into a string separated by commas.

function getDayList(data) {
    var dayNumMap = {"mon":1,"tue":2,"wed":3,"thu":4,"fri":5,"sat":6,"sun":7};
    var list = [], item;
    // loop through all provided days
    for (var day in data) {
        // check if the checkbox is checked
        if (data[day]) {
            item = dayNumMap[day];
            // validate the data
            if (item) {
                // add the day number to the list
                list.push(item);
            }
        }
    }
    // return a comma-separated string
    return list.sort().join(",");
}

// example data from checkboxes
var formData = {"mon":true,"tue":true,"wed":true,"thu":false,"fri":false,"sat":false,"sun":false};

var str = getDayList(formData);

Answer №2

var jsonData = {
  "monday": true,
  "tuesday": true,
  "wednesday": true,
  "thursday": false,
  "friday": false,
  "saturday": true,
  "sunday": false
};

var selectedDays = [], count = 0;
$.each(jsonData, function(day, value) {
  if (value)
    selectedDays.push(count);//<-- index of selected day
  count++;
});

$('#output').text('Selected days: ' + selectedDays.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">please wait ...</div>

Answer №3

Here is an alternative method that can handle missing or disordered object properties:

var obj = {"mon":true,"tue":true,"wed":true,"thu":false,"fri":false,"sat":false,"sun":false}

var s= '';
for(var i in obj) {
  if(obj[i]) {
    s+= 'montuewedthufrisatsun'.indexOf(i)/3;
  }
}
s= s.split('').sort().join(',')
alert(s);

Answer №4

The issue lies in the assumption that the order of object properties will remain consistent during iteration, allowing for easy mapping of property names to indexes like "mon" being mapped to 0. However, this is not guaranteed to be the case across all browsers.

According to the for..in statement, it iterates over the enumerable properties of an object in arbitrary order.

To ensure a more reliable and predictable approach, it is recommended to include the mapping value within the object itself.

var days = {"mon":{index:0,value:true},"tue":{index:1,value:true}};
var val = getConcatanatedDays(days);
function getConcatanatedDays(obj) {
    var val = [];
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop) && obj[prop].value) {
            val.push(obj[prop].index);
        }
    }
    return val.join(',');
}

Another option is to store the days in an array to avoid storing the day values separately and to allow for easier looping through the array.

var days = [{"mon":true},{}];//ordered iteration

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

I'm looking to transform this array into the format described below, and also include another nested subarray within it using TypeScript

[{ "header": "API", "value": "hello" }, { "header":"API", "value":"yellow" }, { "header":"Other", "value":"yallow"}, { "header":"other", "value":"othertt" } ] I have a list of objects with he ...

What is the process for cancelling a RestAngular promise that includes a .then()

What is the best way to cancel a RestAngular promise .then()? I'm unsure about how to cancel a promise/xhr request using restangular/$http - it seems more straightforward in jQuery. ...

Unable to showcase Mysql search outcomes in a distinct div section

I have been working on a project to showcase MySQL results by utilizing three different sections/divisions. In Division 1, there are radio buttons that allow for selecting and viewing the results based on different criteria. Division 2 contains text indica ...

What is causing my page to automatically refresh whenever I click on buttons?

The code snippet below shows the structure of my webpage : HTML : <button class="add-col"><i class="fas fa-columns"> Add a column</i></button> <div class="table-responsive"> <table class="table"> ...

AngularJS: Retrieve country, state, and city data from a database for selection

I am looking to implement a country, state, and city selection feature on my website. I already have separate tables for countries, states, and cities in my database. City Table CREATE TABLE IF NOT EXISTS `cities` ( `city_id` int(11) NOT NULL, `city_ ...

Tips for developing a directive that supplies values for ng-options

I have select elements with the same options throughout the entire app, but they may vary in appearance. For example, selects for a user's birthday (day, month, year). Is it possible to create a directive that can provide values or expressions for ng ...

Populate select2 with the selected value from select1 without the need to refresh the page or click a button

Being a novice in PHP and Javascript, I am looking for a way to populate the "info" select dropdown based on the selected value from the "peoplesnames" dropdown without refreshing the page or using a button. Here's my code: HTML: <select id="peo ...

Discovering the exact latitude and longitude coordinates along a specific route using Google Maps

I've encountered a problem with finding the latitude and longitude along a given route using Google Maps DirectionsService. I have a JSON dataset containing latitude, longitude, and price details. My goal is to plot markers on the map and determine wh ...

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Unable to retrieve the /socket.io/socket.io.js file in the client-side application

My server side application is currently hosted on heroku: The code snippet that is relevant to this issue is as follows: const express = require('express'), app = express(), server = require('http').createServer(app), ...

What is the best way to implement an anchor link in my JavaScript code?

I'm struggling to wrap my head around this, as my thoughts seem to have vanished. On my webpage, there's a button element with an id: for example <button id="someId"></button> Within the document.ready function, I've set up an ...

Show the chosen option when the textarea is no longer in focus

My form includes a text box and a button: <p><textarea rows="4" cols="30">Aliquam erat volutpat.</textarea></p> <p><input type="button" value="Submit"></p> When the user selects text in the textarea and then cl ...

Calculating the size of an array in MongoDB using the aggregate

I am currently developing a platform that connects developers with designers, and I'm looking to enhance the popularity ranking algorithm. Here is the current code snippet: project_collection.aggregate([ { "$project": { "score": ...

Information utilized in an angular template must be sourced from a designated controller

namespace MyApp.Component.CarInfo { angular.module(MY_APP).component('bmwCarInfo', { template: ` <span> <strong>30-Day Evaluation Period</strong> <br />Charges will ...

Experience seamless axis rotation in THREE.js using mouse input and the powerful THREE.Quaternion

Attempting to create a fluid rotation for THREE.Object3D using mousemove without any jitter, gaps, interruptions, or other issues. I have tried various approaches including nested groups but haven't been successful yet. Perhaps using Quaternions will ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

Utilize both parent component styling passed down through props and component-specific styling in React Native

Can specific styling properties be set from the parent component as props while others are set within the component itself? Below is the code for the component: import React,{ Component } from 'react'; import { View, Text } from 'react-nat ...

Transferring a method through two layers of hierarchy

I'm currently working on a fun little game project, but I've hit a roadblock when it comes to passing a particular method down to its grandchildren components. Despite finding similar discussions on this topic, none seem to address my specific qu ...

Switching to a different view in a React Native application

I am encountering difficulties while navigating between pages in my React Native application. Whenever I try to use the button, an error message pops up saying: TypeError: undefined is not an object (evaluating '_this.props.navigation'). My app c ...

Uploading files on a web page using AJAX technology

I'm attempting to perform a file upload on an ajax response page. The main.php file contains basic ajax code as shown below: <html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if ...