Arrange items according to a different object

From the HTML structure, I have generated the following array:

const sort = [{ section_id: 'b', children: ['2'] }, { section_id: 'a', children: ['1', '3'] }]

Each object in this array represents a section, where children is an array of content ids belonging to that section.

There is also a product object:

const product = {
            id: 'asd',
            title: 'product title',
            sections: [
                { id: 'a', title: 'section with id a', contents: [{ id: '1' }] },
                { id: 'b', title: 'section with id b', contents: [{ id: '2' }, { id: '3' }] }
            ]
}

The goal is to "re-create" the product object based on data coming from sort. The expected result would be as follows:

const sortedProduct = {
            id: 'asd',
            title: 'product title',
            sections: [
                { id: 'b', title: 'section with id b', contents: [{ id: '2' }] },
                { id: 'a', title: 'section with id a', contents: [{ id: '1' }, { id: '3' }] }
            ]
}

A function has been written to achieve this, but the output is not as expected. Please provide guidance on what might be incorrect in the implementation.

const SrtProduct = () => {
    const sort = serializeSections() // returns array as in example
    let sortedProduct = {}
    sortedProduct.sections = []
    const emptySection = {
        _id: '',
        contents: [],
        title: ''
    }
    Object.keys($productStore).forEach(key => {
        if(key !== 'sections') sortedProduct[key] = product[key]
    })

    sort.forEach((section, index) => {
        sortedProduct.sections[index] = emptySection
        let pozycja = getIndex(product.sections, section.id)
        Object.keys(product.sections[index]).forEach(key => {
            if(key !== 'contents') sortedProduct.sections[index][key] = product.sections[pozycja][key]
        })

        if(section.children.length > 0) section.children.forEach((content_id, ind) => {
            let poz = getContentIndex(product.sections, content_id)
            let tmp = sortedProduct.sections[index]
            tmp.contents.push(product.sections[poz[0]].contents[poz[1]])
            sortedProduct.sections[index] = tmp
        })
    })

    return sortedProduct
}

The current output is:

...
sections: [
                { id: 'a', title: 'section with id a', contents: [{id: '2'}, {id: '1'}, {id: '3'}] },
                { id: 'b', title: 'section with id b', contents: [{id: '2'}, {id: '1'}, {id: '3'}] }
            ]

The helper functions getIndex and getContentIndex are functioning correctly.

getIndex returns the position in the array where a section with the given id is found. For example, getIndex(product.sections, 'b') would return 1

getContentIndex For instance, getContentIndex(product.sections, '2') would return [1,0] (section position 1, content position 0)

Input: product, sort

Output The sortedProduct which rearranges the sections and contents according to the information from sort

Answer №1

Upon reviewing your code, it seems that there are some errors present. Specifically, the use of section.id will result in an undefined value due to looping over sort, which only contains section_id and not id. However, I have made some modifications to your code to achieve the desired output.

const SrtProduct = () => {
  const sort = [{ section_id: 'b', children: ['2'] }, { section_id: 'a', children: ['1', '3'] }];
  const $productStore ={
    id: 'asd',
    title: 'product title',
    sections: [
      { id: 'a', title: 'section with id a', contents: [{ id: '1' }] },
      { id: 'b', title: 'section with id b', contents: [{ id: '2' }, { id: '3' }] }
   ]
 };
 let sortedProduct = Object.assign({}, $productStore);
 sortedProduct.sections=[];

 sort.forEach((section, index) => {
   let product_sections_index = $productStore.sections.findIndex(x => x.id ===section.section_id);
   sortedProduct.sections[index] = $productStore.sections[product_sections_index]

   sortedProduct.sections[index].contents = [];
   section.children.forEach((value,index2) => {
     sortedProduct.sections[index].contents[index2] = {id: value};
   })
 })

 return sortedProduct
};

You can view/run the updated code here

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

Tips for resolving import errors encountered after running npm start

I recently started using React and I am currently following a tutorial. Even though I have the exact same code as the tutorial, I'm encountering the following error. ./src/index.js Attempted import error: './components/App' does not have a ...

What could be causing the 'Invalid element type' error to occur in my React Native application?

`import { StyleSheet, Text } from 'react-native'; import { Provider } from 'react-redux'; import { store } from './store'; import { HomeScreen } from './screens/HomeScreen'; import { SafeAreaProvider } from 'rea ...

html elements correspond directly to individual json objects

Looking for a precise way in javascript/jquery to connect objects created in an external JSON file to populate their respective HTML divs. The code snippet and JSON data are provided below, along with an image for reference that shows the layout of the div ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. https://i.sstatic.net/vBtXc.png When there are more than 9 items, the current layout ...

Prevent the form from refreshing while still allowing for submission

I'm currently working on a radio website that features a player and several banners that can be clicked on to play different radios. In my opinion, the ideal behavior would be that when I click on a button to play a radio, it should smoothly transiti ...

Identify the nature of two related sets

In my code, I have a variable named al : 'a list, a function called a_to_b : 'a -> 'b, and another function named score : 'b -> int. The portion of the code that states let bl = List.map a_to_b al in ... defines bl : 'b list. ...

Tailwind Component Grid in Action

I'm trying to arrange a list of JavaScript components in a grid with one row and twelve columns. I want to use only six columns for the actual elements, while having three columns of padding on each side of the grid. My goal is to place three elements ...

Adding two double arrays together using AVX vectorization technique

I'm looking for a way to add the elements of two double arrays together and store the result in a third array. Currently, I have the following simplified function: void add( double* result, const double* a, const double* b, size_t size) { memcpy( ...

Secure Your Knockout JS Applications with These Development Tools

In my MVC / SPA application, I have implemented several knockout functions where variables are assigned to allow them to be called from other functions. This setup enables updating elements on the page and making server calls when necessary. All primary k ...

What could be causing my dropdown menu code to malfunction?

Having trouble with the drop-down menu! I used "display: none;" in CSS to hide the list, but I'm not sure if it's the best way. This idea was borrowed from a Codecademy project. I know there may be some cringe-worthy code here, but please bear w ...

Is Three.js application compatible with mobile browsers?

I'm working on an application that relies on the Three.js library. Unfortunately, I've run into an issue where it doesn't seem to work on mobile browsers when using WebGLRender. I've looked at some applications created by Mr.doob () for ...

What is the most effective method for isolating a particular number within a string of text?

Suppose you have a string in the following format: Randy Test 10000 1 aValue 3.5mL bValue 4.0mL What is the most efficient approach to extract the values 3.5 and 4.0 and convert them to integers? One method I considered was splitting the string based on ...

A guide to mastering Controllers in AngularJS

Trying to set up a basic page with a controller but encountering difficulties. The HTML code is straightforward, with an Angular script included, but the functionality isn't working as expected. The HTML snippet: <!DOCTYPE html> <html ng-ap ...

Encountering a 404 error when accessing my Node get URL

As a newcomer to Node.js, I am feeling a bit overwhelmed after reviewing some code examples below. I simply want to add some APIs to an existing project, but for some reason, I keep getting a 404 error. Here is the content of app.js: var createError = req ...

Why did the Mongoose fail to cast to ObjectID for this value?

I'm facing an issue where I know what the problem is, but can't wrap my head around why it's happening. In my simple recipe app that utilizes express and mongoose, users input recipe information through a form which is then saved to the data ...

Performing numpy's fast Fourier transform on an array of numpy arrays in Python

Looking for an efficient way to perform np.fft.fftn on an array of 2D numpy arrays? Consider the following scenario: V0 is an array with a shape of (nvar, nx, ny), and you want to carry out FFT on each 2D array along the first dimension of V0. In the code ...

Clicking an element causes popovers to vanish

I have encountered an issue with my popovers. I am trying to trigger them through a function that is called by an onclick event. Strangely, they disappear within a second. They work fine when checked individually, but once the user presses the "submit" but ...

Strategies for effectively engaging with dynamically created forms amidst a multitude of other forms on a webpage

One of the challenges I face is dealing with a page that has multiple forms dynamically generated based on user input. Each form contains two sets of radio buttons, with the second set being disabled by default and enabled based on the users' selectio ...

Perform operations such as addition, subtraction, and comparison of date and time in Meteor Mongo

Currently, I am working with a collection on Meteor Mongo that includes two important fields: last_activity and expire_date. One scenario involves retrieving items from this collection based on their last_activity being N hours in the past. In another si ...

Is there a workaround to prevent me from using overflow: scroll when I addEventListener("touchmove", preventBehavior, false)?

I am developing an iOS app using PhoneGap, and I have encountered a problem where the window cannot be moved due to the code document.addEventListener("touchmove", preventBehavior, false); Although this code prevents the window from moving, it also stops ...