Looking to convert this single object into an array of objects within VueJS

So, I've encountered a bit of a pickle with the data from an endpoint that I need to format for a menu project I'm working on. It's all jumbled up and not making much sense right now. Any assistance would be greatly appreciated!

This is the original data:

{
  SubMenu: {
    Main: [
      {
        Main: "Database",
        SubMenu: {
          Name: "Manage",
          Path: "databaseManage",
          icon: "mdi-database",
          innerMenu: "false",
        },
      },
      ...
    ],
  },
},

Here is how it should look:

[
  {
    main: "Databases",
    submenu: [
      {
        name: "Manage",
        path: "databaseManage",
        icon: "mdi-database",
        innerMenu: false,
      },
      ...
    ],
  },
  ...
],

I've tried using computed properties, as well as Object.keys and values, but haven't been able to reach a solution yet. Can anyone provide some guidance?

Answer №1

My function is designed to achieve the desired outcome.

function organize(arr) {
var result = [];
for (let j = 0; j < arr.length; j++) {
    if (result.some(item => item["main"] === arr[j]["Main"])) {
        let index = result.findIndex(y => {
            return y['main'] == arr[j].Main;
        });
        let duplicate = arr[j].SubMenu;
        result[index].submenu.push(duplicate)
    } else {
        let duplicate = arr[j]["SubMenu"]
        let object = {
            main: arr[j]["Main"],
            submenu: [duplicate]
        }
        result.push(object);
    }
}
return result;
}

If you provide the Main array as input, this function will successfully carry out the task.

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

Is it possible to iterate through a JSON file payload item by item?

We have a JSON file with 2 records. I need to read each record individually and send it to a REST API. Can these records be retrieved in a list or must they be sent one by one instead of in a single payload? How can we split them? { "batchSize": 0, ...

A guide to identifying duplicate elements in an array with Python

Just started learning Python and I'm looking for a way to create a new list of unique users. The issue I'm facing is with the following data: [ { "userId": "987654321", "method": "CARD", " ...

What is the best way to display JQuery mobile tap event information in real-time?

I am experiencing an issue in my code where the tap event is being triggered, but the array[i] value is printed as null. Whenever I click on any index, it always prints an empty string (" "). Why does it display null instead of the clicked value? I am see ...

In CodeIgniter, when there are multiple entries with the same ID in a foreach loop, the elements can be summed

I am using a foreach loop to create a table with data from the "sale" row, specifically json_decode($row['sale']). Currently, each entry is being displayed separately. However, my goal is to display entries with the same id [product_id] as one ro ...

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

Convert JSON data into an HTML table with custom styling

If you have a set of JSON data that you want to convert into an HTML table, you can use the following code: $.each(data, function(key, val) { var tr=$('<tr></tr>'); $.each(val, function(k, v){ $('<td>' ...

What is the best way to ensure that a JSON request aligns with a model or dto entity

I am facing an issue related to Spring/JPA. Let's say I have a request in this format: model/BillDto.java public class BillDto { private String desc; private Long id; private Integer amount; public BillDto(String desc, long id, i ...

The ajax signal indicates success, yet there seems to be no update in the database

Hey there, thank you for taking the time to read this. Below is the code I'm currently working with: scripts/complete_backorder.php <?php if(!isset($_GET['order_id'])) { exit(); } else { $db = new PDO("CONNECTION INFO"); ...

Is there a way to insert a space between the double quotes and colon in the dictionary's key values?

Check out my code snippet below: import json def generate_value_list(sentence): word_list = sentence.split(" ") total_number_of_words_in_the_sentence = len(word_list) value_list = [] for i in range(0, total_number_of_words_in ...

What are some ways I can customize the appearance of this Google Maps infoWindow?

I was able to create a Google Maps script using JavaScript code. The map displays multiple locations with corresponding latitude and longitude coordinates. This script can be viewed at . My objective now is to customize the appearance of the info windows ...

Utilizing jQuery to convert object properties into a table

Here is the table structure I am working with: <table> <thead> <tr> <th>Loan Type</th> <th>Amount Borrowed</th> <th>Current Payment< ...

`sendNodejs header not being transmitted during connection``

My nodejs application utilizes stomp to connect to a server using websockets. However, I am encountering an issue where the application is failing to send the headers that I have specified. Despite referring to clear documentation and examples on how to in ...

Creating POST requests using the FormData API

I am trying to pass the username and form_data object to a PHP file using http.post. When I only pass form_data, my picture upload works fine. However, I also want to pass some other information like the username. Can someone please help me with how to p ...

Changing the display of elements using Javascript in IE6 by modifying class

Currently, I am facing an issue at work that involves a piece of code. The code functions correctly in Firefox 3.6 where clicking on a row changes its class name and should also change the properties of the child elements. However, in IE6 and possibly othe ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...

What could be causing the error message "setShowModal is undefined" to appear in my React project?

Here is the code snippet I am working on: import React, { useState } from "react"; import Modal from "./Modal"; function displayModal() { setShowModal(true); } export default function NewPostComponent() { const [showModal, setShowMod ...

What is the best way to convert a Date into the JSON format before sending it to the database?

I'm currently delving into backend development with Node.js, and I am in the process of connecting my backend to a MongoDB. Specifically, I am working on creating a User object that includes Birth Date as one of its properties. However, I am strugglin ...

Enable contenteditable on table by pressing the tab key

I developed a table entry tool and I would like to be able to input items by pressing the tab key instead of having to manually click on each element. I haven't been able to figure out how to make this function work yet. $('table').on(&apos ...

Is it possible to use a '.JS' file downloaded through Node Package Manager (npm) directly in a web browser?

Generally, I am looking to utilize a specific library without relying on Node CMD. For instance: I aim to create a TypeScript playground without having to execute 'tsc.cmd' from "npm\node_modules", instead, I want to directly call the tsc c ...