Combining two distinct array objects

Attached below is my JSON:

"mainSteps": [
  {
    "id": "9b3b64b4-d8a5-46d5-b464-066dc5c45dc3",
    "name": "Main Step 1",
    "steps": [
      {
        "name": "sub step 1.1"
      },
      {
        "name": "sub step 1.2"
      }
    ]
  },
  {
    "name": "Main step 2"
    "steps": [
      {
        "name": "sub step 2.1"
      },
      {
      "name": "sub step 2.2"
      }
    ],
  },
  {
    "name": "Main Step 3",
    "steps": [
      {
        "name": "sub step 3.1"
      },
      {
        "name": "sub step 3.2"
      }
    ],
  }
]

I am looking for the desired output format like: [Main Step 1, sub step 1.1 , sub step 1.2], [Main Step 2, sub step 2.1 , sub step 2.2], [Main Step 3, sub step 3.1 , sub step 3.2]. I have spent the entire day trying to achieve this output but keep getting different formats such as [[Main Step 1, Main Step 2, Main Step 3, sub step 1.1, sub step 1.2....]. Despite trying various methods, I cannot seem to obtain the exact output as mentioned above. Can someone provide me with some clarification?

var dataProcess = {
        parentProcess:[],
        subProcess:[]
                           };                      
   var steps = mainData.steps; // Steps containing the full JSON data                   
        var proc = [];
                 $scope.getSteps = function(steps) {
                    for (var i=0; i < steps.length; i++) {
                       dataProcess.parentProcess.push(steps[i].name);
                     for(var j=i; j < steps[i].steps.length; j++){
                  dataProcess.subProcess.push(steps[i].steps[j].name);
                   }
                   }

This is one of the methods I have tried so far.

Answer №1

In case ES5 syntax is required:

var details = mainSteps.map(function(step) {
  return [ step.name ].concat((step.steps || []).map(function(substep){
    return substep.name;
  })
});

Alternatively, for ES6 syntax:

var details = mainSteps.map(step =< [step.name].concat((step.steps || []).map(sub => sub.name));

If deeper recursion is necessary, a function can be used as the top level mapper that calls itself.

Answer №2

Perhaps you could approach it in this manner:

let primarySteps = [
  {
    "id": "9b3b64b4-d8a5-46d5-b464-066dc5c45dc3",
    "name": "Primary Step 1",
    "steps": [
      {
        "name": "sub step 1.1"
      },
      {
        "name": "sub step 1.2"
      }
    ]
  },
  {
    "name": "Primary Step 2",
    "steps": [
      {
        "name": "sub step 2.1"
      },
      {
        "name": "sub step 2.2"
      }
    ],
  },
  {
    "name": "Primary Step 3",
    "steps": [
      {
        "name": "sub step 3.1"
      },
      {
        "name": "sub step 3.2"
      }
    ],
  }
],
mapped = primarySteps.map(e => [e.name, e.steps[0].name, e.steps[1].name]);
console.log(mapped);

Answer №3

By implementing this approach, the code is designed to handle arrays of different lengths and subarrays:

var results = mainSteps.map(x => [x.name].concat(x.steps.map(y => y.name)));

Answer №4

A straightforward approach using Array.map and Array.concat methods:

// Assuming "obj" is the initial object
var dataProcess = obj.mainSteps.map(function (o) {
    return [o.name].concat(o.steps.map(function(v){ return v.name; }));
});

console.log(JSON.stringify(dataProcess, 0, 4));

The result:

[
    [
        "Main Step 1",
        "sub step 1.1",
        "sub step 1.2"
    ],
    [
        "Main step 2",
        "sub step 2.1",
        "sub step 2.2"
    ],
    [
        "Main Step 3",
        "sub step 3.1",
        "sub step 3.2"
    ]
]

View DEMO 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

Utilize res.render in Node.js to pass multiple data arrays to the view

I am facing an issue with populating two separate selects in my view with different arrays. Can anyone guide me on how to pass two distinct JSON objects using res.render? I have attempted the method below without success. const result1 = {data1: "val ...

What is the reasoning behind websites predominantly opting for new windows for authentication as opposed to using pop-up dialogs or iframes?

In developing a widget that prompts for authentication when clicked on a third-party site, I've noticed that most websites use pop-up windows for this process instead of in-page dialog boxes like inserted iframes. I'm curious about the security i ...

JSON interprets HTML as text rather than parsing it

I am currently working on a WordPress theme that heavily utilizes Ajax. I am parsing the requested post data into an encoded JSON, printing it out, and then using json.parse to interpret it. Subsequently, I am utilizing Handlebars to showcase the data in ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...

Buttons failing to adjust the color of the background and text

There seems to be an issue with this piece of code. I can't quite put my finger on it, but something is definitely off. I am trying to make it so that when a button is clicked, the background color and text font changes. Unfortunately, this is not wo ...

Challenges arise when attempting to modify an ArrowHelper without creating a new instance

In my project using three.js, I am facing a challenge with updating the components of 3 ArrowHelper. Currently, I am able to update these 3 ArrowHelper in my animation by creating new instances each time the drawing function is called. For instance, in my ...

Issues arise when using ng-repeat in conjunction with ng-click

I am facing some new challenges in my spa project with angularjs. This is the HTML snippet causing issues: <a ng-repeat="friend in chat.friendlist" ng-click="loadChat('{{friend.friend_username}}')" data-toggle="modal" data-target="#chat" d ...

fetch and modify data simultaneously in firebase

Is there a way to retrieve a value from a Firebase document and immediately update it? I am familiar with methods for updating documents and retrieving their values separately, but how can I accomplish both in one go? update firebase.firestore().collecti ...

"Enhance your website with Wordpress and Divi by adding dynamic image replacement on hover

In search of a code to insert into my project Utilizing images to create a large interactive button I'm currently using the divi code module within WordPress. I am seeking the ability to have an image switch with another image when hovering over it, ...

What is the best method for retrieving a single DataRow object from an Asp Web API?

Currently, I am in the process of developing Asp.Net WebApi code that needs to connect with some outdated C# back-end code where model classes are not utilized. Instead, pure dataTable is returned from DataAccess (I know, it sounds crazy) Below is the cod ...

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

When utilizing JSON tag, an empty array [] is returned, which conflicts with gson's expectation

I am currently utilizing the GSON Library for parsing my JSON data. In some cases, certain tags are expected to contain string values (not arrays). The issue arises when an element ends up being empty [], resulting in this error message displayed on the c ...

How to efficiently reduce an array in ES6 without encountering any TypeScript errors

Is there a way to efficiently remove the first array element without modifying the original array (immutable)? I have this code snippet: function getArray(): number[] { return [1, 2, 3, 4, 5]; } function getAnother(): number[] { const [first, ...rest ...

Interactive Button Animation using Three.js

After importing a Mesh element into three.js from an fbx file, I am looking to enhance it with an effect similar to that of a clickable button. I am aiming to achieve the same pushable button effect as demonstrated in the first button style found on http ...

An external script containing icons is supposed to load automatically when the page is loaded, but unfortunately, the icons fail to display

Hello and thank you for taking the time to read my query! I am currently working in a Vue file, specifically in the App.vue where I am importing an external .js file containing icons. Here is how I import the script: let recaptchaScript2 = document.creat ...

difficulty arises when attempting to invoke a viewmodel from another viewmodel inside a ko.computed function

Is it possible to have two view model functions in my JavaScript where one references the other? I am encountering an error with this setup. Here are my view models: var userViewModel = function (data) { var _self = this; _self.ID = ko.obs ...

Select a division and retrieve the identification of a different division

I am looking to trigger an event by clicking on one element and extracting the ID from a separate, unrelated div. Here is my attempt: $(".map_flag").on("click",function(){ var selectedID = ($(this).attr("data_modal")); $("#" + selectedID).fade ...

Guide to converting a Lookup<string, string> object to JSON format

I'm attempting to convert a Lookup object into JSON using the following code: Lookup<string, string> productIdsByCategory = prodcuts.ToLookup(p => p.Category, p => p.Id); Next, in my ASP.NET Core WebAPI controller, I am sending the respo ...

The process of incorporating user properties into the output of a Service Bus topic from a Javascript Azure Function

I'm currently developing a TypeScript Azure Function that utilizes an Azure Service Bus topic as its output. Although I am able to send messages successfully, I have encountered difficulties in setting custom metadata properties for the message. In m ...

Preventing JavaScript from Removing Operators When Transmitting/Storing Data in PHP with AJAX

My goal is to transmit a string equation, like "3+3", but when PHP processes it, it displays as "3 3" instead. It seems that somewhere along the way, the operators are disappearing. function sendEquation() { let str = document.querySelector(".equation ...