What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this:

[types.GET_PRODUCT_CATEGORIES] (state,{ stores }) {
        state.product_categories = {}
        console.log(stores);
        stores.forEach(message => {
            set(state.product_categories, message.id, message)
        })
        console.log('test')
        console.log(state.product_categories)
    },
    

When I use console.log(stores), the output is as follows:

I am looking to transform this object into a two-dimensional array based on parent_category_id key.

Could someone guide me on how to achieve this?

Update :

For example:

parent_category_id = 1, 2, 3

parent_category_name = asia, europa, africa

id = 4, 5, 6, 7, 8, 9, 20

name = japan, korea, arab, england, spain, italy, south africa

The desired display format would be:

asia
       japan
       korea
       arab
    europa
       england
       spain
       italy
    africa
       south africa
    

Hence, the need to convert the one-dimensional object into a two-dimensional structure.

Answer №1

May this solution guide you towards success

var dataArr=[{
id:1,
name:'japan',
parent_category_id:1,
parent_category_name:'asia'
},{
id:2,
name:'england',
parent_category_id:2,
parent_category_name:'europa'
},{
id:3,
name:'korea',
parent_category_id:1,
parent_category_name:'asia'
},{
id:4,
name:'arab',
parent_category_id:1,
parent_category_name:'asia'
},{
id:5,
name:'south africa',
parent_category_id:3,
parent_category_name:'africa'
},{
id:6,
name:'spain',
parent_category_id:2,
parent_category_name:'europa'
},{
id:7,
name:'italy',
parent_category_id:2,
parent_category_name:'europa'
}],
output ={};
dataArr.map((item,index,arr)=>{
if(!output[item.parent_category_name]){
let result = arr.filter(val=>{
return val.parent_category_id==item.parent_category_id;
})
output[item.parent_category_name] = result.map(val=>{
return val.name;
});
}
});
console.log(output);

Answer №2

Check out this custom function I use for grouping data:

const groupItems = (arr, keySelector) => {
  const groupedItems = arr.reduce( (grouping, item) => {
    const key = keySelector(item);
    grouping[key] = grouping[key] || [];
    grouping[key].push(item);
    return grouping;
  }, {} );
  return Object.keys(groupedItems)
    .map(key => { return {key: key, items: groupedItems[key]}; });
}

You can utilize it in this manner:

const itemsByCategoryName = (items) => {
  const keySelector = item => item.parent_category_name
  return groupItems(items, keySelector)
    .map(group => { return { parent_category_name: group.key, grouped_items: group.items }; });
}

The result is an array of objects containing a key and a nested array of items.

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

How to Retrieve Element Property Values from the DOM with JavaScript

I am currently attempting to access the property of an element within my webpage. My main objective is to toggle a float property between left and right when a specific onClick event occurs. However, despite my efforts, I am facing challenges in even acces ...

A step-by-step guide on masking (proxying) a WebSocket port

Within my server-side rendering React app, I have set up a proxy for all HTTP calls to a different port. Take a look at the code snippet below for the HTTP proxy configuration. import proxy from "express-http-proxy"; const app = express(); const bodyParse ...

Jquery events continue to accumulate without initiating until the preceding event has completed

Looking at the code below, it essentially fades all the images to 70% within the contact class. When an image is hovered over, its opacity changes to 100%. If multiple images are hovered over or multiple hover events occur in succession, the events will st ...

Postman is showing an error when making a request using Express.js app.get()

Recently, I started working with Express.js and I am using Postman to test my API. When running the code below, I successfully retrieve all members from the object: // gets all members app.get('/api/members', (req, res) => { res.json(membe ...

What is the best way to retrieve the value of a checked radio button in React.js?

I am in the process of creating a well-structured to-do list and I want to be able to add the input from any selected radio button into one of three options arrays (the array is not included in the code, but rather in a parent component). I am looking fo ...

How to dynamically bind items in vuejs

I have a basic select that I would like to bind to an array. My framework is Vuetify, but this issue is common across platforms. <v-select v-bind:items="physicianListSpeciality" > </v-select> Now I want to use the same select for multiple arr ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Iterating through typescript enums in Vue using v-for

Why is the v-for loop over an enum displaying both names and values? Is there a way to iterate only over the keys? export enum Colors { "RED" = 1, "BLUE" = 2, "GREEN" = 3, } <template> <div> <v ...

Comparison between bo-html and bo-text

As I was going through the documentation for the bindonce directive, a question popped into my head regarding the distinction between bo-html and bo-text. bo-html: This evaluates "markup" and displays it as HTML within the element. bo-text: ...

Navigating through the DOM using JavaScript or regular expressions

I have a DOM string called innerHTML and I am looking to extract or display the node value using either JavaScript's DOM API or JavaScript RegEx. "<nobr> <label class="datatable-header-sortable-child" onmousedown="javascript:giveFeedback(&ap ...

Error message malfunction on the Express.js server side

Here is the server-side POST code that I am using. Before saving my task to the database, I am trying to find data in the database using a unique value called service. However, when I run this code, the console displays an error: ReferenceError: service is ...

Using jQuery to show and hide elements on a webpage

One issue I'm facing is changing the content on a page depending on the clicked link. The problem arises when the displayed content for one link persists even after clicking another link, despite setting it to not display when another link is clicked. ...

Next.js Refresh Screen

Is there a way to refresh my client's web page from the server at a specific time? I need the client's page to be refreshed at 12pm, and although I'm using a scheduler, it doesn't seem to be automatically refreshing the web page on the ...

"How to set the header in AngularJS when opening a new window with a GET request URL

Can anyone provide guidance on setting headers and opening a URL (https://www.example.com) in a new window without including sensitive authentication information in the URL parameters? I am working with AngularJS for this task. I have searched through exi ...

How can I utilize the "remark" tool to handle Markdown files with URLs that don't adhere to Markdown formatting? Are there any supplemental plugins available for this

My markdown file has frontmatter and sometimes includes inline URLs that are not properly formatted with markdown syntax. I'm looking for a way to handle these non-markdown URLs within the markdown file - possibly by parsing them into HTML URLs using ...

Tips for removing "<li>" elements using JavaScript

My issue remains unresolved... I created a tree structure in MVC and added JavaScript code for expanding and collapsing the tree. However, after applying the code, my tree is not being displayed correctly. enter image description here In the image, you c ...

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

Should I implement this practice when developing an AJAX website? Is it recommended to enable PHP code within .html files, or should I switch to using .php files instead?

Query: I am interested in executing PHP within HTML documents to include HTML using PHP include();. Question: Would it be more beneficial to change .php to .txt for my AJAX-loaded pages and switch my .html files to .php? This approach might resolve the ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...