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:

https://i.sstatic.net/bzM8I.png

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

"Contrasting the Execution of a JavaScript Function in a .js File Versus an HTML

I'm struggling with calling a JavaScript function inside an HTML page. Interestingly, when I move the function into an external file and link it, everything works perfectly. Can someone provide assistance in resolving this issue? Below is the content ...

What is the best way to trigger a JavaScript function using an HTML button?

I am trying to trigger a JavaScript file from an HTML component by clicking on a button, but nothing happens when I click the button: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> < ...

The information is not being shown. Error: API expression GET is not possible

import express from 'express'; import data from './data'; const app = express(); app.get("/api/products", (req, res) => { res.send(data.products); }); app.listen(5500, () => {console.log("The server has been successfully s ...

Is it possible to access the Firebase user object beyond the confines of the Firebase function?

Despite successfully logging users into my application using Google Auth from Firebase, I am facing an issue where the User object does not display on the front end of my application (which utilizes Pug templates). How can I resolve this? The code snippet ...

Is there a way to remove a particular map from Firestore?

In my Google Firebase setup, I have uniquely named each Map to serve as the index for every document. Using Vuejs (Javascript), I have structured it as follows: eQFelbD432T (Collection Name- user.uid) SKILLS (Document Name) ProjectManangement (Map Na ...

Using Django to Display a Line Chart with Data from a Dictionary in a Template

I have a dictionary that was generated in the views.py file. The structure of the dictionary is as follows, but it contains data for an unspecified number of enterprises: { enterprise1: {'Year': ['2014/2015', '2016/2017', &ap ...

how to handle form submission using JavaScript's return method

As a developer, I have created a single page that fetches data from a registration page. On this page, each data row has an "add" and "unfriend" button, with the latter initially disabled. When a user clicks the "add" button, a prompt box appears asking ...

Sending JSON data parsed by oboe.js to the http response object in a Node.js server

Using Oboe.js for JSON parsing from a Node readStream with the aim of sending it back to the requesting client in a memory-efficient manner. I'm exploring the possibility of piping data from Oboe's node or path events to a Node.js HTTP response o ...

Unable to configure node and express for file serving

Currently using Windows 7, I have successfully installed nodes 0.10.12 and the latest versions of express and express-generator globally. I then proceeded to create a new express project called nodetest1 and installed all dependencies using npm install. U ...

Angular 4 in combination with ngx-datatable is showing a 404 error for the @swimlane/ngx-datatable package

Just starting out with Angular and I kicked things off by running this command: git clone https://github.com/angular/quickstart appName I've made the upgrade to Angular 4 and everything seems to be in order. Here's the output I got after running ...

How to show a placeholder in a select input using ReactJS

I'm currently trying to incorporate placeholder text into a select input field using ReactJS, but it doesn't seem to be working as intended. Here is the code snippet I am working with: <Input type="select" placeholder="placeholder"> ...

Analyzing and tallying JSON attributes using JavaScript

I have a JSON object with items that I need to analyze in JavaScript. When I view the JSON in the console, there is an element called items that contains an array of relevant information. console.log(json) {current_page: 1, per_page: 100, total_entries: ...

What is the process for creating a line using points in three.js?

Can anyone provide a solution for creating a straight line using new THREE.Points()? I attempted to place particles and set their positions with an array and for loop, but the spacing was inconsistent. ...

Leveraging JQuery to Invoke Partial View

I have a partial view in my /Shared folder that is defined as follows: <div id="myProducts"> @Html.Partial("_ProductsList",Model) </div> I am attempting to refresh the _ProductsList view using jQuery. Specifically, I wan ...

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

Retrieving status code without reliance on a back-end language (maybe through JavaScript?)

My new service offers a solution for error pages in web apps by providing a code snippet that can be easily copied and pasted into the error page templates, similar to Google Analytics. The status code is embedded in a hidden input within the installatio ...

Exploring the seamless integration of Material UI with React version 18

I am having an issue with my background not turning black in React version 18.2.0 when using makeStyles from Material UI version 4. Despite no errors in the code, the background remains unchanged. How can I fix this problem? import './App.css'; i ...

Make sure to execute the fire directive only when ng-repeat has completed

Currently, I am utilizing owl carousel with data being fetched through an Ajax call. Once the data populates the HTML content using ng-repeat, I need to trigger the directive that initializes the owl carousel. How can I achieve this? One approach I consid ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

Guide on adjusting the CSS styling of elements in real-time from the backend using a user customization panel to modify the appearance of various web pages

Imagine a scenario where we have a website consisting of multiple pages, including a user account page. The user has the ability to modify the color, font size, and style of certain elements on other pages for their own viewing preferences. How can this fu ...