Using Ramda to transform an array of key-value pairs into an object

Utilizing Ramda to organize a normalized model object by key involves converting it to key|value pairs (similar to Object.entries) and sorting by the first value using R.head (which represents the key when in pairs)

The goal is to transform the resulting sorted array of pairs into an array of objects. In the code snippet below, ES6+ map and array destructuring are used for this purpose

const data = {
  2: {name: 'two'},
  1: {name: 'one'}
}

const sortByKey = R.compose(R.sortBy(R.head), R.toPairs);
const sortedPairs = sortByKey(data)
console.log(sortedPairs)
// [["1",{"name":"one"}],["2",{"name":"two"}]]

const objs = sortedPairs.map(([key, value]) => {
  return {[key]: value}
})
console.log(objs)
// [{"1":{"name":"one"}},{"2":{"name":"two"}}]

The challenge lies in finding a suitable Ramda function for the following task:

const objs = sortedPairs.map(([key, value]) => {
  return {[key]: value}
})

Answer №1

By using R.map along with R.objOf, you can easily transform an array of pairs (key, value) into an array of objects.

const { compose, map, apply, objOf, sortBy, head, toPairs } = R

const sortByKey = compose(sortBy(head), toPairs)
const arrayFromPairs = map(apply(objOf))

const data = {
  2: {name: 'two'},
  1: {name: 'one'}
}

const result = arrayFromPairs(sortByKey(data))

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

Answer №2

One way to create an object from a single pair is by using the compose(fromPairs, of) function.

const fromPair = compose(fromPairs, of);
fromPair(["a", 1]);
//=> {"a": 1}

const { compose, fromPairs, head, map, of, sortBy, toPairs } = R;

const sortByKey = compose(sortBy(head), toPairs);
const fromPair = compose(fromPairs, of);
const arrayFromPairs = map(fromPair);

const data = {
  2: {name: 'two'},
  1: {name: 'one'},
};

const sortedPairs = sortByKey(data);
const objs = arrayFromPairs(sortedPairs);
console.log(objs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>

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

Loading Disqus comments dynamically upon clicking a button within a Next.js application

After noticing a significant decrease in page performance scores due to Disqus comments embedded on Vercel Analytics, I am considering implementing a "Load comments" button instead of loading the actual comments onClick. I have been using the disqus-react ...

The interplay between javascript and PL/SQL tasks in a dynamic scenario

I'm attempting to run multiple pl/sql blocks within a Dynamic Action, providing real-time feedback to the user through a modal dialog displaying the current status. Here is an example of what I am trying to achieve: Processing Step 1... /*Run pl/s ...

Error: Unable to access properties of an undefined value (trying to read 'type') within Redux Toolkit

Looking for help with this error message. When trying to push the book object into the state array, I encounter an error. Folder structure https://i.stack.imgur.com/9RbEJ.png Snippet from BookSlice import { createSlice } from "@reduxjs/toolkit" const ...

Using querySelector to Target Elements by their InnerHTML Content

Is it possible to target an element by its innerHTML directly without the use of loops? Is there a way to achieve this with something like document.querySelector('div[innerHTML="Sometext"]') or document.querySelector('div[textcontent="Som ...

Is there a way to activate a function in one component from another within a Next.js application?

As mentioned in the title, I am working with 2 custom components within a basic NextJS application: <section> <CompA></CompA> <CompB></CompB> </section> I am trying to figure out how to have a button inside Comp ...

Sending the format of the display value to an Angular component

Looking for a way to pass display value formatting to an Angular component. Here are a couple of examples: format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)' or format="'(tz, offset) location'" === &a ...

React-Image-Annotate encountered an issue: SyntaxError - The import statement cannot be used outside a module

Encountering an issue while trying to set up react-image-annotate. Here is the problem I am facing initially: https://i.stack.imgur.com/XgYPd.png This is how I have implemented it: import React from 'react' import ReactImageAnnotate from ' ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

error is not defined in the onsuccess function of the ajax.beginform partial view

Currently, I am working on an MVC5 project where a View is calling a Partial View. Within the Partial View, there is an Ajax.BeginForm that triggers a function on OnSuccess. However, during execution, I encounter an error stating that the function cannot ...

What is the best way to hide the jQuery modal I created?

Hello everyone! Currently, I am working on coding a simple JS modal that can be opened and closed smoothly. The issue I am facing is related to adding a click function to (.black-overlay) in order to fade out everything and close the modal. <div class ...

The jquery UI button is displaying too wide even though the padding is set to zero

My goal is to decrease the width of certain jQuery buttons. Though I have attempted to eliminate padding using the code below, there remains a minimum of 5 pixels on either side of the text within my button. .button().css({ 'padding-left':' ...

My node.js and express application is encountering an issue where it is failing with an error indicating that a variable has not been

Currently in the process of understanding how node.js and express operate. I've successfully extracted data from my mongo database... and now I'm experimenting with transferring data between my router code and views. The locations.js file within ...

Enhance the visual appeal of mandatory input fields in virtuemart by incorporating star symbols

Is there a way to incorporate red stars into the form for mandatory input fields within Virtuemart 1.x? ...

Is there a way to access data from a different cart template containing personalized values on Shopify?

After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible ...

Execute JavaScript function in NodeJS server background

I have developed a function that periodically monitors the battery statuses of connected android devices and returns an array. How can I execute this function on server startup and ensure it continues to run while sharing its information with other pages? ...

Transform Image on Hover in ReactJS

I am working on a Card Component that includes an image and text. Initially, the image is redImage and the text is black. When hovering over the card, I want the redimage to change to whiteimage and the text color to change to white as well. The content ...

What is causing the ng-show function to malfunction after building with phonegap?

My current javascript framework for my PhoneGap app is the Ionic Framework. I have a specific item on one of my pages that I want to make expandable and collapsible by clicking an anchor on the page. Here is what the code looks like: In the HTML file: & ...

PHP query Ajax navigation

UPDATED I have made progress with processing both menus in "process.php" and displaying the queries in index.php. process.php <?php $menu1 = $_POST["menu1"]; $menu2 = $_POST["menu2"]; if($menu1 == 0) { $sql = "SELECT * FROM Language WHERE ID = " ...

Using JavaScript to add a class when hovering over an element

I am trying to customize the ul inside one of my li elements in the nav by adding a class when hovered. However, I am encountering an issue where the menu disappears when I try to click on it after hovering over it. I want to achieve this functionality usi ...

Exploring the interception of ajax http responses beyond the scope of AngularJS

Is there a way to capture and manage http responses from outside of Angular? $httpProvider is not an option since the target script loads after Angular has initialized. I need a solution that functions similar to ajaxSuccess in jQuery. ...