Use Ramda to convert an array of objects into nested objects

As a beginner, please forgive me for asking what may be considered a naive question.

I currently have an array of objects

const arr = [{id: 1, name: 'Pete'}, {id: 5, name: 'John'}, {id: 3, name: 'Peter'}]

and I am looking to transform it using Ramda into the following structure:

const obj = {1 : {id: 1, name: 'Pete'}, 5: {id: 5, name: 'John'}, 3: {id: 3, name: 'Peter'}} 

Could someone kindly assist with this?

Other Conceptual Questions:

  1. I am contemplating converting a nested array of objects into this format in order to optimize searching by name when given an id. Is this approach sound?
  2. Are there any alternative, more efficient methods that could improve search performance within the array?

Many thanks

Answer №1

If you're looking to streamline your search process, consider utilizing Ramda's R.indexBy method:

const array = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]

const result = R.indexBy(R.prop('id'))(array)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

Transforming a nested array of objects into this structure can greatly improve search speed when querying by ID. Is this considered the most efficient approach?

Retrieving an item from an array typically has a time complexity of O(n), whereas extracting an item from an object (indexed by a property) operates at O(1) efficiency, making it the superior choice for searching by id. However, if your focus is on finding an object based on its name, indexing by the name property would be more appropriate. Consider whether searches will involve exact matches or partial matches within names. If the latter applies, iteration through the entire array may still be necessary with a complexity of O(n).

Are there alternative strategies that offer better performance for accelerating search operations within arrays?

The optimal solution hinges on your specific search requirements and the volume of items being queried. For datasets up to approximately 50,000 entries and searches predominantly targeting id, implementing an object or Map could yield improved efficiency. Conversely, if searches revolve around partial name matches, sticking with an array might suffice. It's advisable not to prematurely optimize until encountering actual performance issues, conducting profiling to pinpoint any search-related bottlenecks.

Answer №2

If you don't have ramda, one option is to utilize the built-in Object.fromEntries method along with a mapping of id and object.

const
    array = [{ id: 1, name: 'Pete' }, { id: 2, name: 'John' }, { id: 3, name: 'Peter' }],
    object = Object.fromEntries(array.map(o => [o.id, o]));

console.log(object[2].name);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Utilizing Map can significantly improve the efficiency in this scenario.

const map = new Map();
const data = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]

for(const {id, name} of data){
  map.set(id, name);
}

//check for id presence
map.has(1)  // true
//retrieve person's name
map.get(1) //"Alice"

Answer №4

If you want to keep the original array as it is and get a new array with only specific matches, you can use a filter method:

const data = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]


let result = data.filter(item => item.id == 1);
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

Seeking materials for WebDriverJs?

It has come to my attention that there are some valuable resources available: http://docs.seleniumhq.org/docs/03_webdriver.jsp https://code.google.com/p/selenium/wiki/WebDriverJs However, I am curious if there exists a comprehensive website that prese ...

Create a page turning effect in React that simulates scrolling a certain amount at a time

Is there a way to disable default scrolling and have the page automatically scroll to the next item? For example, if I have element2 below element1, how can I set it up so that when I scroll down once, the page scrolls directly to the position of element2 ...

What is the importance of moving prop types into a type or interface in React components?

Consider the scenario where I have a functional component: const MyText = ({ value }) => ( <div className="my-fancy-text">{value}</div> ); Now, when utilizing Typescript, I face the need to introduce typing. A straightforward ...

Utilizing req.session in an Express application with Angular (written in TypeScript) when deploying the backend and frontend separately on Heroku

I'm currently facing an issue where I am unable to access req.session from my Express app in Angular. Both the backend and frontend are deployed separately on Heroku. I have already configured CORS to handle HTTP requests from Angular to my Express ap ...

Modify picture properties when listbox is altered using jQuery

I need to set up a unique album gallery display where different folders are selected based on the item chosen in a selectbox. Below is the HTML code: <select name="album" id="album" onChange="changeimage();"> <option value="0" selected disab ...

Is it possible to meet the requirements of a specific interface using an enum field as the criteria?

I've been struggling to create a versatile function that can return a specific interface based on an enum argument, but all my attempts have failed. Could it be possible that I missed something or am simply approaching it the wrong way? If I try to ...

Guide to highlighting a particular letter in a string variable using JavaScript and AngularJS

Looking to highlight specific letters within a string variable. I have the string stored as an AngularJS variable in a table like this: <td>{{variable}}<td> In my JavaScript file, I am passing a variable for Angular that contains the string & ...

What strategies can I implement to integrate Cordova with a combination of Meteor and React?

I'm currently struggling to implement a Cordova plugin with Meteor and React. According to the documentation: You should wrap any functionality that relies on a Cordova plugin inside a Meteor.startup() block to ensure that the plugin has been fully ...

Issue with Firebase CLI preventing deployment of Cloud Functions

I'm currently working on an Angular project, and I'm facing a challenge in deploying a single Firebase function. Here's how my functions directory is structured: When I run the command firebase deploy --only functions to deploy the function ...

"Data is not defined" error message is triggered when using jQuery DataTable Row Details

While utilizing jQuery Data Tables to construct a datatable with row details, I encountered an error in jquerydatatables.js: data is undefined The JavaScript code being used is: $(document).ready(function() { var dt = $('#tbl_cheque_history' ...

Variations in ajax requests coupled with a polling mechanism

Suppose the initial ajax call is made right away, and the function called by the controller keeps looping until it reads something, as shown below: def FirstAjax(): while True: if something is read: val = something brea ...

Modifying elements in an array using iteration in typescript

I'm trying to figure out how to iterate over an array in TypeScript and modify the iterator if necessary. The TypeScript logic I have so far looks like this: for (let list_item of list) { if (list_item matches condition) { modify(list_ite ...

Issue with readonly is preventing the ability to alter the font color of the input

I need to change the font color of a disabled input. When it is disabled, it appears gray and I want it to be black instead. I attempted to use readonly but that did not have the desired effect, and now the input is showing [object Object]. Below is my HTM ...

What is the best way to assign multiple values to certain elements within an array?

I have an array that looks like this: items = { item1: 10, item2: 5, item3: 7, item4: 3, }; I am looking to include additional details in this array, for example: items = { item1: 10 {available: true}, ...

Utilizing Google Maps API to automatically set an address on page load

As a beginner in using the Google Maps API, I have successfully integrated a Google Map into my project. However, I am struggling to figure out how to set specific addresses on the map. I have a list of 2,000 entries in a database, each including an addres ...

React: Remove a particular row from the table

I am currently working on a project that involves building a table component. Each row in this table is also a separate component. class FormulaBuilder extends Component { constructor(props) { super(props); this.state = ...

Error: Uncaught object in AngularJS ngRoute

I keep encountering an uncaught object error in my browser console while trying to load my AngularJS application. I am unsure if this issue is related to ng-route.js or if it's something else, as the error message only says 'uncaught object' ...

Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data. CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001 Hard coded data: info:[ { "id": 1, "title": "Title one ...

Is it possible to transfer a specific feature from jQuery to Prototype?

I find myself in a situation where I have to use Prototype instead of jQuery, even though I'm not as familiar with it. Can anyone assist me in transforming the following script: var output={}; $$('ul li').each(function(item){ var firstL ...

Looking for a way to streamline data transfer using script setup in Vue 3? Consider utilizing composables to simplify the process

In the scenario where there is a parent component labeled as "1" with two child components named "2" and "3", each of these components containing its own child component, "4" for "2" and "5" for "3", the challenge arises on how to pass state from child c ...