"Utilizing Ramda's map function to integrate dynamic keys: A step-by-step guide

I am currently working with an array structured like this :

array = ['2020-06-03', '2020-06-05', '2020-06-06']

My task is to transform it into the following format :

Object {
  "2020-06-03": Object {
    "selected": true,
    "selectedColor": "#ff5555",
  },
  "2020-06-04": Object {
    "selected": true,
    "selectedColor": "#ff5555",
  },
  "2020-06-05": Object {
    "selected": true,
    "selectedColor": "#ff5555",
  },
}

This is my current approach :

const historyDates = map(date => {
      return { selected: true, selectedColor: "#ff5555"};
    }, array);

The issue I am facing is that I need to include keys in the new object created. How can I achieve this using Ramda expressions? Additionally, I am aware that I am returning a mapped array instead of an object filled with sub-objects.

Any assistance or guidance would be greatly appreciated.

Answer №1

When using the R.map function, which behaves similarly to the native Array.map(), it returns an array. By creating an array of objects with the original values as keys and then merging them into a single object, you can achieve the following:

const { pipe, map, mergeAll } = R

const fn = pipe(
  map(k => ({ [k]: { selected: true, selectedColor: "#ff5555"} })),
  mergeAll
)

const array = ['2020-06-03', '2020-06-05', '2020-06-06']

const result = fn(array)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

Another approach is to generate an array of [key, value] pairs and then convert it into an object using R.fromPairs:

const { pipe, map, fromPairs } = R

const fn = pipe(
  map(k => [k, { selected: true, selectedColor: "#ff5555"}]),
  fromPairs
)

const array = ['2020-06-03', '2020-06-05', '2020-06-06']

const result = fn(array)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

If you prefer vanilla JavaScript, you can achieve the same result using Array.map() and Object.fromEntries():

const fn = arr => Object.fromEntries(
  arr.map(k => [k, { selected: true, selectedColor: "#ff5555"}])
)

const array = ['2020-06-03', '2020-06-05', '2020-06-06']

const result = fn(array)

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

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

Tips on attaching a suffix icon to a material-ui-pickers input box

Here is a snippet of my code: <Box p={6}> <Grid container spacing={2}> <Grid item xs={6}> <TimePicker autoOk label={t('checkIn')} value={time1} onChange={handlecheckIn} clearable /> </Grid> < ...

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...

Executing a scroll down action with Selenium in combination with Node.js and the Chai/Mocha testing framework

Browser: Chrome Looking for ways to scroll up or down using Selenium with Node.js (JavaScript). ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

What methods do you suggest for storing the app's state in the browser to reduce the number of requests to the backend?

Recently at work, I encountered an issue with our application that is generating unnecessary requests and causing performance issues. Our technology stack consists of Typescript, React, and Redux (not Redux-Toolkit). I am seeking the following outcomes: ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Why is the current Menu Item highlight feature not functioning properly?

Why isn't the highlight current Menu Item feature working? I've checked my code, but it doesn't seem to be functioning as expected. Could you lend me a hand? Html: <section id="menu-container"> <div id="bar"><img src="b ...

Utilize AngularJS to create a concealed input field

Currently utilizing angularjs, you can find the code at this link Desired Outcome: When the add button is clicked, I want the value of $scope.todotest to appear along with the text in the textbox. Issue Faced: Upon adding for the first time, the date d ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Creating a live child component using React

My issue lies with the menu component, which is supposed to dynamically load elements in another container component. Unfortunately, the child elements are not being rendered. App.js import React, { Component } from 'react'; import './App. ...

Managing errors and error codes in React/Redux applications

I am currently exploring the most effective approach for managing errors, particularly when deciding between error codes and an errors object in response from my API. As I dive into building a multi-part form using react, each time a user progresses to th ...

Successful jQuery Ajax request made without the need for JSON parsing

I find it strange that my experience with jQuery's ajax function is completely different from what I'm used to. Below is the javascript code in question: $.ajax({ url: "/myService.svc/DoAction", type: "GET", dataType: "json", su ...

implementing a timestamp in a specific timezone with Vue.js

Utilizing a timestamp attribute, I have successfully implemented the display of the current time and date on my webpage. Is there a way to showcase this information in a specific time zone? I am looking to present it in the ZULU timezone, which remains st ...

Tips on emphasizing all div elements and incorporating navigation to each of them

I am seeking a method to enhance a div with highlighting when there is a click or mouseover event. For instance, changing or adding a border color using JavaScript on click or mouseover is straightforward. Recently, I have been contemplating the idea of a ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

Dynamic modal in Vue JS with custom components

Within the news.twig file {% extends 'layouts.twig' %} {% block content %} <section class="ls section_padding_bottom_110"> <div id="cart" class="container"> <cart v-bind:materials=" ...

Conceal any ng-repeat elements that do not contain corresponding grandchildren within two levels of nested ng-repeats

Apologies for the enigmatic title, but the issue at hand is quite cryptic ¯\_(ツ)_/¯ I'm dealing with a complex problem involving 3 nested ng-repeats to display Google Analytics' account structure. Within this structure are multiple acco ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

script to pause video using jQuery

I have a script that works perfectly, but currently it only stops an instance of a playing video if a new video is started. I want to modify the script so that ALL instances of playing videos are stopped when the function stopAllButMe(); is called. Can s ...