A TypeScript example showcasing a nested for-of loop within several other for loops

Is it possible to generate values from an Array of objects in the following way?

const arr = [
  {
    type: "color",
    values: [
      {
        name: "Color",
        option: "Black",
      },
      {
        name: "Color",
        option: "Blue",
      },
    ],
  },
  {
    type: "size",
    values: [
      {
        name: "Size",
        option: "XS",
      },
      {
        name: "Size",
        option: "M",
      },
    ],
  },
];
let oldArr: any[] = [];
if (arr.length === 1) {
  for (const iterator of arr[arr.length - 1].values) {
    oldArr.push(iterator);
  }
} else if (arr.length === 2) {
  for (const iterator of arr[arr.length - 1].values) {
    for (const iterator2 of arr[arr.length - 2].values) {
      oldArr.push([iterator, iterator2]);
    }
  }
} else if (arr.length === 3) {
  for (const iterator of arr[arr.length - 1].values) {
    for (const iterator2 of arr[arr.length - 2].values) {
      for (const iterator3 of arr[arr.length - 3].values) {
        oldArr.push([iterator, iterator2, iterator3]);
      }
    }
  }
} else if (arr.length === 4) {
  for (const iterator of arr[arr.length - 1].values) {
    for (const iterator2 of arr[arr.length - 2].values) {
      for (const iterator3 of arr[arr.length - 3].values) {
        for (const iterator4 of arr[arr.length - 4].values) {
          oldArr.push([iterator, iterator2, iterator3, iterator4]);
        }
      }
    }
  }
}

Can this be done recursively N times with real Array of objects given?

The expected output needed is an array of arrays:

 const oldArr = [

[
    {
        "name" : "Color", 
        "option" : "Blue", 
    }, 
    {
        "name" : "Size", 
        "option" : "XS"
    }
],
[
    {
        "name" : "Color", 
        "option" : "Black", 
    }, 
    {
        "name" : "Size", 
        "option" : "XS"
    }
],
[
    {
        "name" : "Color", 
        "option" : "Blue", 
    }, 
    {
        "name" : "Size", 
        "option" : "M"
    }
],
[
    {
        "name" : "Color", 
        "option" : "Black", 
    }, 
    {
        "name" : "Size", 
        "option" : "M"
    }
]
]

What other details should be included before posting this?

Answer №1

Presented here is a recursive function that should yield the desired results. Extensive testing has been done with inputs up to 4 nested loops, all producing successful outcomes. The arguments are fairly self-explanatory; arr represents the array being read, oldArr signifies the array being written to, vals acts as a list for tracking iterator values (begin with an empty list), level indicates the "recursion level," and target_level specifies the final recursion level sought after. To utilize this function, consider running something like

recursive_func(arr, oldArr, [], 1, 4)
to mimic the behavior of your example with 4 nested loops.

If the number of nested for loops always matches the length of arr, kindly inform me so adjustments can be made to simplify the function.

function recursive_func(arr, oldArr, vals, level, target_level) {
    for (const it_n of arr[arr.length - level].values) {
        vals.push(it_n);
        if (level == target_level) {
            oldArr.push(JSON.parse(JSON.stringify(vals)));
        } else {
            recursive_func(arr, oldArr, vals, level + 1, target_level);
        }
         vals.pop()
    }
}

const arr = [
  {
    type: "color",
    values: [
      {
        name: "Color",
        option: "Black",
      },
      {
        name: "Color",
        option: "Blue",
      },
    ],
  },
  {
    type: "size",
    values: [
      {
        name: "Size",
        option: "XS",
      },
      {
        name: "Size",
        option: "M",
      },
    ],
  },
];
let oldArr = [];
recursive_func(arr, oldArr, [], 1, arr.length);

console.log(oldArr);

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

Vue js is throwing an error because it is unable to find the "buscador" property or method that is being referenced in the render function

I am currently diving into the world of laravel combined with Vue js. I am working on integrating a search engine using vue js components, and I would greatly appreciate any help you can provide. Thank you in advance. Below is the Vue js component where t ...

Implementing Pagination in Vue: How to Make it Work with Response Data

I am looking to integrate pagination from the response data into my existing code, while also incorporating filters. JavaScript var entriesList = new Vue({ el: "#post-list-template", data: { posts: [], categories: [], cu ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...

What is the best way to set an initial value retrieved from the useEffect hook into the textField input field?

I am working on an edit page where the initial values of first name, last name, and address are fetched from Firebase Firestore using useEffect. useEffect(() => { const unsubscribe = firestore .collection("users") .doc(uid) ...

The property is returning an empty string, but the function is functioning perfectly

Check out this related Stack Overflow post exports.getAddress = asyncHandler(async (req, res, next) => { var lon = req.query.lon; var lat = req.query.lat; var formattedAddress = ""; var url1 = 'url' request(url1 ...

What is the quickest way to redirect a URL in WordPress?

Is it possible to redirect a URL instantly in WordPress using this script code? JavaScript Code: jQuery(document).ready(function() { var x = window.location.href; if (x == 'http://example.com/') { window.location.hr ...

Clarifying the concept of invoking generic methods in TypeScript

I'm currently working on creating a versatile method that will execute a function on a list of instances: private exec<Method extends keyof Klass>( method: Method, ...params: Parameters<Klass[Method]> ) { th ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

How can React and react-router be used to direct users to a specific group of URLs

One scenario I have is when my users upload a group of photos, they need to add specific meta information for each one. After uploading the files, I want to direct them to the first photo's meta editor page. Then, when they click on the "next" button, ...

Enhanced approach to building with React and Express

Quick Summary: How can I set up a project using React on the front-end and Express on the back-end with just one package.json and node_modules folder? When starting a project that combines a React front-end and an Express back-end, my desired structure is ...

Using ng-repeat and selectize in AngularJS to populate a multi-select drop-down with values and set selected values

In this instance, I was able to achieve pure HTML select multiple functionality by using this example (JS Bin of pure html select tag). However, instead of sticking to just the pure HTML approach, I opted to use the Selectize plugin. The confusion arose w ...

Can you explain the distinction between ajaxComplete and beforesend when making an Ajax call with JavaScript?

Can you explain the usage of ajaxComplete and beforesend? What sets them apart from each other? Are there any alternative methods similar to success when making an Ajax call? ...

Transformation of visuals with alteration of status

I am attempting to change the image of a door from closed to open when the status changes in my home automation dashboard. I need help with this task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&qu ...

Exploring jasmine testing with ajax requests

I've been working on writing Jasmine unit tests for a JavaScript file that includes an Ajax call. I'm unsure how to properly test the 'Success' function using Jasmine. Here's a snippet of the code: function getGroups(){ var defe ...

Solutions for concealing the current div when clicking on a new div that reveals a fresh one

Is there a way to hide the current div once you click on a new div that reveals another one? The code below toggles the display of the div, but what I am attempting to achieve is that when you click on a new item after clicking on the first one, the first ...

Animate jQuery Images - Transform and smoothly reveal element

Hey there! I've managed to create a color switcher that gives a sneak peek of different themes. Currently, it simply switches the image source and loads the new image. But I'm curious if it's possible to add a fadeIn effect to enhance the t ...

Heroku is showing an Error R10 (Boot timeout) message, indicating that the web process was unable to bind to the designated $PORT within one minute of launching

Encountering an error while trying to deploy my first node project on Heroku. Here is the error message: 2020-09-29T04:24:09.365962+00:00 app[web.1]: production 2020-09-29T04:24:09.415266+00:00 app[web.1]: server is listening at port 40890 2020-09-29T04:24 ...

Having Multiple File Inputs [type=file] in one webpage

Is it possible to have two separate inputs for uploading images, each setting a different background image in a div? The second file input is: <input type='file' id='getval' name="logo" /> I want this file to be set as the back ...

What is the best way to ensure that the swf loads only after all the images and text have loaded completely

Is there a way to use jQuery to control the loading of SWF files on my CMS system? Sometimes when a video is included in the SWF file, it uses up bandwidth and makes the page non-responsive for a while. I would like the SWF files to load after the other co ...