Transform the structure of an object using Ramda from its original form

Is it possible to transform an object by modifying and filtering it to create a different shape that is easier to work with after making an API request? I've been struggling to find elegant solutions that don't involve using path and prop for every key.

It seems like there should be a more efficient way to reshape objects without explicitly specifying each property. Can anyone suggest a more concise approach?

I've experimented with functions like evolve and lens, but I haven't been able to achieve the desired outcome of adding new properties easily.

Edit: I managed to create a mapping function that gets the job done, but I'm curious if there's a better method out there.

Here's what I tried:

const { prop, path, toUpper, map, compose } = R

const baseObject = {
  id: 1,
  name: 'object-one',
  info: {
   items: [
      { name: 'item-one', url: '/images/item-one.jpg' },
    ]
  },
}

const createObjectFromSpec = spec => baseObj => R.map(f => f(baseObj), spec);

const createObjectTypeOne = createObjectFromSpec({
  id: prop('id'),
  name: prop('name'),
  image: path(['info', 'items', 0, 'url']),
})

const createObjectTypeTwo = createObjectFromSpec({
  id: prop('id'),
  name: prop('name'),
  itemName: path(['info', 'items', 0, 'name']),
})

console.log(
  createObjectTypeOne(baseObject)
)

console.log(
  createObjectTypeTwo(baseObject)
)

Answer №1

In your provided example, the function createObjectFromSpec can be found in Ramda under the name applySpec.

const fn = R.applySpec({
  id: R.prop('id'),
  name: R.prop('name'),
  image: R.path(['info', 'items', 0, 'url'])
})

const result = fn({
  id: 1,
  name: 'object-one',
  info: {
    items: [
      { name: 'item-one', url: '/images/item-one.jpg' },
    ]
  },
})

console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.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

Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked: $('li').click(function() { $(this).toggleClass('active'); }); My goal is to hide all other li elements in t ...

Leverage PHP variables within AJAX requests

I am currently working on implementing a specific functionality on the page "videos.php" (please note that this is all contained within a PHP echo statement): First, when a user clicks .star_' . $pvid_ID . ', it triggers the submission of a vid ...

Utilizing AJAX to add information to jQuery data tables without taking advantage of their pagination and advanced features

The jQuery datatables plugin is a useful tool for adding filters, pagination, and search functionality to web applications. I have personally integrated it with my Laravel project to organize and display data effectively. Recently, I decided to enhance th ...

The function of cookieParser() is causing confusion

Having an issue that I've been searching for answers to without success. When using app.use(express.cookieParser('Secret'));, how can we ensure that the 'Secret' is truly kept secret? I'm feeling a bit lost on this topic. Is ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

What is the best way to change the value of a div using JavaScript?

i could really use some assistance, i am trying to ensure that only the selected template is shown on the screen, while all others are hidden. The expected outcome should be to replace the values of: <div class="city">City<span>,< ...

Reading properties of undefined in React is not possible. The log method only functions on objects

I'm currently facing an issue while developing a weather website using the weatherapi. When I try to access properties deeper than the initial object of location, like the city name, it throws an error saying "cannot read properties of undefined." Int ...

Ensure redirect is delayed until async data is fetched

Having come from the Angular world, I found it really easy and convenient to resolve data for routes. However, now that I'm using React, I'm unsure about how to achieve the same functionality. I would like to add an async data loader for my rout ...

What are the best plugins and projects to maximize IntelliJ IDEA's potential for JavaScript development?

I am currently in the process of developing a web application utilizing the MEAN stack: MongoDB, Express, Angular, and Node.js. The foundation of my project is built upon Daftmonk's angular-fullstack Yeoman generator. Despite my primary experience be ...

Tips for hovering over a link with Webdriver

Currently, for my project, I am utilizing Selenium Webdriver. Successfully automating the functionality to mouse over an image has been achieved. However, there seems to be an issue when attempting to trigger a mouse-over event on a hyperlink using the sam ...

Unraveling the mystery: Retrieving event.target.value in a React component

Having trouble accessing the event.target.value from a React child Component, but not an HTML tag? In this scenario: the Button tag (React Component) cannot access event.target.value, while the button tag (HTML tag) can. import React from "react"; impor ...

Discovering the size and count of JavaScript objects within a browser's memory

Many suggest using the Chrome Profiler Heap Snapshot to analyze memory usage, but I have found that on an empty page (no JavaScript or CSS, just HTML), it shows a heap size of 8MB and anywhere from 12 to 30 thousand objects depending on its mood. This tool ...

Mastering the art of concurrent Ajax requests using jQuery for an advanced Posting and Commenting system

In my Asp.net MVC project, I have successfully implemented a post and comment mechanism. The posts and comments are stored in different tables in the database. Additionally, using Ajax requests with jQuery, I can retrieve comments from the database and dis ...

Navigating with Angular/Routing through Dynamic Content

Exploring the best approach for managing dynamic content within an angular application has been my recent focus. Currently, I have an array containing phone numbers and aim to organize them based on their respective countries. For instance, all German phon ...

Frequently refreshing a page to display the most recent information without needing to reload the entire

I am seeking a solution for updating the comments section on my website live or every 30 seconds. The comments are fetched from a MySQL database using PHP: <?php $link = mysql_connect('localhost', 'root', ''); ...

Aligning an element perfectly at the top within a column

I have two columns side by side. The column on the left contains HTML that I cannot control. On the right side, I need to display a comment box that should align with the text clicked on the left hand side. Is it possible to position an element absolutely ...

Strategies for Effectively Managing Null Checks in Your JavaScript Project

When retrieving data from the BE API, it is in the format: { "details": { "address": { "street": "123/4", "city": "Banglore" } } } In our React project, we access this dat ...

Establish a timeout period for ajax requests using jQuery

$.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something } }); At times, the success function performs well, but sometimes it does not. How can I add a timeout to this ajax re ...

Transform the specifications to condense all fields containing a nested `name` key

The following data is provided: [ { "id": 123, "foo": "fooooooo", "bar": "bbbbbbarr", "recordtype": { "name": "type123", "some_field": & ...

Choose three different images and one corresponding word from a JavaScript array to be displayed individually on the screen in separate div containers

I am in the process of developing a web game that will showcase 3 images on the screen, and the player must select the image that corresponds to the displayed word. I have successfully created a JavaScript array containing the images and words retrieved fr ...