What is the best way to simplify my data by removing nested references?

Hey everyone, I'm looking for some assistance in organizing certain data effectively while keeping performance in mind. I've been struggling with recursive functions and multiple loops, so I simplified the data to grasp the concept better and solve it with your help. Here's what I have:

const data = [
{
   id: 'W1', 
   color: red,
   personId: 'P77',
},
{
   id: 'W7', 
   color: yellow,
   personId: 'P21',
},
]

const persons = [
{
   id: 'P77',
   name: 'Peter',
   favoriteFoodId: 'FF4',
},
{
   id: 'P21',
   name: 'John',
   favoriteFood: 'FF9',
}
];

const favoriteFood = [
{
   id: 'FF9'
   food: 'pasta'
  description: 'fresh italian pasta from stone oven'
},
{
   id: 'FF4'
   food: 'banana'
  description: 'fresh bananas from the tree'
}
]

I need help merging this data into a flattened structure incorporating all the references. How can I create a generic solution that handles deep nesting and flattens it with all the necessary references? I attempted a solution but ended up looping excessively and it became overwhelming.

I aim to achieve a result similar to this:

const result  = [
{
   id: 'W1', 
   color: red,
   name: 'Peter',
  food: 'banana'
  description: 'fresh bananas from the tree'
},
{
   id: 'W7', 
   color: yellow,
   name: 'Peter',
    food: 'pasta'
   description: 'fresh italian pasta from stone oven'
},
]

The result will be utilized by my table component to render each object as a row

Answer №1

Have you thought about using Dictionaries for this?

const data = 
{
   'W1':{ color: "red" ,  personId: 'P77' }
   ,'W7':{ color: "yellow", personId: 'P21'},
}

const persons =
{
  'P77':{ name: 'Peter', favoriteFoodId: 'FF4' },
   'P21':{ name: 'John', favoriteFoodId: 'FF9' } 
}

const favoriteFoods = 
{
   'FF9':{ food: 'pasta', description: 'fresh italian pasta from stone oven' }
  ,'FF4':{ food: 'banana', description: 'fresh bananas from the tree' }
}

function getFavFood( pId , field ){
  return favoriteFoods[ persons[ data[pId].personId ].favoriteFoodId ][field]
}

// not sure what template library you'll be using
// but for now plain old js....

table = "<TABLE>"

for( d in data){
  table += `<TR style="background:${data[d].color}">`
  + `<TD>${ persons[ data[d].personId ].name }</TD>`
  + `<TD>${ getFavFood( d , "food" ) }</TD>`
  + `<TD>${ getFavFood( d , "description" ) }</TD>`
  +`</TR>` 
}

table += "</TABLE>"

document.body.insertAdjacentHTML( "beforeend" , table )

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

Ways to display the contents of a blank array

My goal is to display the contents of the chat array, which is initialized as an empty global variable, in a table. The information I want to print is received through web sockets and stored in the messageReceived function. I am able to confirm that the ...

What is the best approach to create a form wizard with validation using Vue.js?

I recently completed a Vue.Js project where I created a wizard based on a video tutorial. However, I am facing issues with form validation using the 'is-valid' and 'is-invalid' CSS classes that I have defined. Here is my code: <div c ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

The Android JSON parsing model is encountering a ClassCastException issue where the com.google.gson.JsonObject is unable to be casted to com.google.gson.JsonArray

I recently started exploring Android development and am in the process of building an app that involves using the Zomato Rest API. To interact with this API, I've opted to utilize the Koush ION library which can be found at https://github.com/koush/io ...

What steps can be taken to modify the file that will be launched when the npm start command is executed?

As a beginner in learning react.js, I was instructed by my course instructor to start by installing Node.js and configuring it using the npm init command. This created a package.json file where we then installed lite-server, described as a Node.js server. ...

Mastering the Art of Scrolling

Can someone please tell me the name of this specific scrolling technique? I am interested in using something similar for my project. Check out this example site ...

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

Establishing the state in React using information received from a Java Spring request

I am currently working on a small project with React for the front end and Spring Java for the backend. I am trying to populate a React "state" based on the response from a method in Spring. Here is an example of the Java method: @CrossOrigin(origins = ...

Are there any methods for updating redux-form's submitting property with a workaround?

I have integrated reCAPTCHA v2 with a sign-up form that is using redux-form. The issue I am facing is that when the user submits the form, the reCAPTCHA modal pops up and the redux-form's 'submitting' prop changes from 'false' to & ...

I'm looking to include a field card into the to-do table I built using .Net, but I'm not sure where I made a mistake

HTML Challenge I have set a goal to dynamically add a DOM element using JavaScript when the "Add HTML Element" button is clicked. The process involves clicking the button, which opens a modal for inputting necessary information. After fil ...

A step-by-step guide on decoding JSON data received from the tweepy API

After researching how to scrape tweets using tweepy, I came across a solution based on the first answer of this question. The code provided is as follows: consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = "" import tweepy au ...

"Troubangular: Troubleshooting unexpected behavior when trying to update ngFor after setting a property

Dealing with what seems like a straightforward component here. I'm fetching an array of objects from an API, storing them in a property, and then displaying them in a select list for the user to choose from. When the value changes, I filter the result ...

Using VueJS to transfer data from the main element to child components via router-view

Typically, when I need a variable that multiple child components should access, I usually store it in the data object of my root Vue element and then pass it down to child components through properties. However, since I've started using vue-router, m ...

The PrimeReact components are not displaying the PrimeReact theme properly

I'm currently working on integrating a Menubar component from PrimeReact into my React application. I tried to apply one of the predefined PrimeReact themes by importing it, but the page ended up looking strange. When I imported "./../../node_modules ...

I am unable to retrieve any text from the class as it is returning a null value

Can someone please assist me with two issues I am facing: 1) Firstly, I am trying to match the text of an alert pop-up using the following code: <div class="noty_message message"><span class="noty_text">Uh oh! Email or password is incorrect&l ...

What is the most effective method for transmitting a zip file as a response in Azure functions with node.js?

With the Azure function app, my goal is to download images from various URLs and store them in a specific folder. I then need to zip these images and send the zip file back as a response. I have successfully achieved this by following these steps: Send ...

Removing Repetitions from a List of Classes and Arranging the List Chronologically

Currently facing two separate issues with arrays: 1) In my coding project, I have an array for users used in a tableview. Each user is stored as an object of the 'Users' class: class Users { let userObjectID: String let profileP ...

Tips for loading internal JSON data using $http.get instead of using an external JSON file

I am currently facing an issue where I use a code snippet to load strings from an external json-file. While everything works fine, running the function locally triggers a 'cross origin' problem. As a solution, I attempted to input the strings dir ...