What is the best way to create all possible combinations of key-value pairs from a JSON array?

In my scenario, there is a JSON array with key-value pairs where the values are arrays. Here's an example:

json = {foo:[1,2],bar:[3,4],pi:[5]}

I am looking for a way to generate all possible combinations of these parameters for any number of keys. The desired output would be a list like:

{foo:1, bar:3, pi:5}
{foo:1, bar:4, pi:5}
{foo:2, bar:3, pi:5}
{foo:2, bar:4, pi:5}

Answer №1

Utilize the reduce function and for each loop to create fresh permutations during each iteration:

const data = {alpha:[10,20],beta:[30,40],gamma:[50, 70], delta: [10]};

const output = Object.keys(data).reduce((accumulator, key) => {
  const tempArray = [];
  
  data[key].forEach(element => {
    if (!accumulator || !accumulator.length) { // Initial iteration
      tempArray.push({[key]: element});
    } else {
      accumulator.forEach(object => {
        tempArray.push({...object, [key]: element});
      });
    }
  });
  
  return tempArray;
}, []);

console.log(output);

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

What is the best way to sort through data retrieved by a server component in a NextJS 13 AppDir?

I've hit a roadblock trying to integrate a search bar that filters server-fetched data in my project using NextJS 13 and AppDir. Despite numerous attempts, I can't seem to get it right. It feels like there's something crucial I'm overlo ...

What is the process of creating a global variable in Node.js?

My task involves calling an API that will return a JSON object stored in a variable. I need to print part of this JSON object on the console. However, I am facing an issue where I can't load the data to the console outside of the request{} loop. How c ...

"Troubleshooting a blank screen issue during JSON data retrieval on an Android device

I have a scenario where I am retrieving a large JSON response from a specific URL. The issue is that when the response is being fetched, the application displays a blank or black screen. To mitigate this problem, I would like to implement a ProgressDialog ...

Combining two RxJs observables to create selectable options for a material drop-down menu

I'm encountering issues while attempting to combine two different observables and display the results in a Material Select component. This example (created using the Material docs tool) demonstrates what I'm trying to achieve. However, the optio ...

Implementing the jQuery datepicker in Angular.js can be challenging

I recently started learning Angular.js and have been working on a web application using this framework. I am now looking to include a datepicker in one of my forms. Below is the code snippet that I have implemented: app.js myapp.directive(& ...

The process of using JsonConvert.DeserializeObject must persist even in the face of encountering various property types, all while accumulating a comprehensive list of any

Is there a way to deserialize a class with properties of different types (int, float, string, guid) and handle errors when a value does not match its expected type? If a value does not match its expected type, can an error be added to a list without halti ...

What is the best way to halt the ticking of this clock in JavaScript?

I can't seem to figure out how to stop this clock using JavaScript Even though I press the stop button, the clock keeps running <!DOCTYPE html> <html> <head> <h1> Welcome to the clock. Press the stop button to halt the clo ...

Unable to implement a personalized error message for HttpMessageNotReadableException in a Spring Boot application

Currently, I am working on implementing custom error messages for exceptions, but I have encountered an issue specifically with HttpMessageNotReadableException. Within my codebase, there is an ErrorDetails class defined as follows: public class ErrorDeta ...

Optimizing the management of data retrieved from the backend in React

My web application follows this flow: When on the Investments screen, an API request is made to a server, returning an array of investment objects that are then displayed as a list. Clicking on an item redirects the user to the Investment Details screen, ...

Interaction between the Vue parent and any child component

I am working with a series of components that are structured in multiple levels. Each component has its own data that is fetched over AJAX and used to render child components. For instance, the days parent template looks like this: <template> &l ...

Having issues with my JavaScript timer - seeking assistance in troubleshooting the problem

Trying to set a timer for my little game, but facing some difficulties. The timer causes the balance to randomly increase from 0 to 13000 + some extra amount. <script> var coins = 0; var speed = 1; </script> <center> <h4> ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

Is it true that Vue 3 + Inertia automatically removes event listeners upon component unmounting?

There is an event listener set up within the script setup block: <script setup> import {ref} from 'vue' const elementRef = ref(null) window.addEventListener('click', (event) => { if (!elementRef.value.contains(event.t ...

Transfer and transform numerous arrays between Android and PHP server

Being new to Android, I am struggling with converting this array into a JSON array and sending it to the PHP server: {"menu":[{"id":"2","number":"3"}, {"id":"6","number":"4"}, {"id":"5","number":"6"}], "user":[{"uid": "12345","number":"<a href="/cdn- ...

Confusion surrounding asynchronous functions in Node.js

When handling routes or endpoints with multiple operations, I often encounter scenarios where I need to perform additional actions. For instance, when deleting an item, it's necessary to also remove the related file from S3 along with deleting the col ...

Error in NodeJs: Port 3000 is already in use due to the utilization of socket.io and express

I've developed a node.js application using socket.io and express. The code snippet is as follows: const express=require('express'); const app=express(); const http=require('http').Server(app); app.use(express.static('public&ap ...

What advantages does incorporating SSR with dynamic imports bring?

How does a dynamic imported component with ssr: true differ from a normal component import? const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), { ssr: true, }); What are the advantages of one method over the ...

reasons for utilizing `this.initialState = this.state;`

Could someone help me understand why I am using this.initialState in a React JS class component setup? class Registration extends Component { constructor(props) { super(props); this.state = { username: '', email: '&apo ...

Ways to show a div element within an input field?

I want to incorporate tags similar to stackoverflow on my website. Users will be able to create tags for filtering results, searching, showcasing expertise, and more. I have managed to create tags, but I am struggling to display them inside an input box l ...

Tips for seamlessly transitioning <img src="..." /> using jQuery?

Currently, I am working on the following code snippet: $img.hover(function(){$(this).attr('src','1.jpg')},function(){$(this).attr('src','2.jpg')}); However, this is not providing a smooth transition as it takes a c ...