Unleashing the power of Javascript to generate all possible combinations of multiple arrays of objects

I am seeking to generate a comprehensive list of combinations from two arrays of objects.

The JSON files I have are:

Fruits

[
  {
    "food": "Apple",
    "calories": 100
  }
],
[
  {
    "food": "Orange",
    "calories": 150
  }
]

Meat

[
  {
    "food": "Chicken",
    "calories": 175
  }
],
[
  {
    "food": "Steak",
    "calories": 200
  }
]

I want to display all possible combinations of objects in the arrays:

Apple 100 Chicken 175

Apple 100 Steak 200

Orange 150 Chicken 175

Orange 150 Steak 200

Currently, I have a simple for loop that is not giving me the desired output:

 for(let i = 0; i < Fruits.length; i++) {
  for(var j = 0; j < Meat.length; j++)
    {
       combos.push(Fruits[i] + Meat[j])
    }
  };

The result I get is:

[
  '[object Object][object Object]',
  '[object Object][object Object]',
  '[object Object][object Object]',
  '[object Object][object Object]'
]

When using map function, I get a bit closer but still unable to access the objects:

combos.map(combo=> {console.log(combo)})

This gives:

[object Object][object Object]
[object Object][object Object]
[object Object][object Object]
[object Object][object Object]

Looking for guidance on how to access these objects or if they are defined there at all.

Thank you for your help!

Update: By adjusting indexes and adding brackets, I was able to achieve my goal with this code:

for(let i = 0; i < this.arrBreakfasts.length; i++) {
  for(var j = 0; j < this.arrLunches.length; j++){
      this.combos.push([this.arrBreakfasts[i][0], this.arrLunches[j][0]]);
  }
};

Thank you!!

Answer №1

This is the correct way to accomplish the task:

for(let x = 0; x < Fruits.length; x++) {
  for(var y = 0; y < Meat.length; y++)
    {
       combinations.push([Fruits[x], Meat[y]])
    }
  };

Your mistake lies in attempting a mathematical operation involving objects.

Answer №2

const vegetables = [
  [{ food: 'Broccoli', calories: 50 }],
  [{ food: 'Carrot', calories: 75 }]
];

const grains = [
  [{ food: "Quinoa", calories: 150 }],
  [{ food: "Brown rice", calories: 120 }]
];

const mealCombos = [];

vegetables.forEach(veggie => grains.forEach(grain => mealCombos.push([veggie, grain])));

mealCombos.forEach(combo => console.log(JSON.stringify(combo, null)));

Answer №3

To properly merge the properties of different objects, you should concatenate the properties instead of the objects themselves.

for(let i = 0; i < Fruits.length; i++) {
  for(var j = 0; j < Meat.length; j++){
       combos.push(Fruits[i][0].food + " " + Fruits[i][0].calories + " " + Meat[j][0].food + " " + Meat[j][0].calories);
  }
};

Demonstration:

const Fruits = [
  [
    {
      "food": "Apple",
      "calories": 100
    }
  ],
  [
    {
      "food": "Orange",
      "calories": 150
    }
  ]
];
const Meat = [
  [
    {
      "food": "Chicken",
      "calories": 175
    }
  ],
  [
    {
      "food": "Steak",
      "calories": 200
    }
  ]
];
let combos = [];
for(let i = 0; i < Fruits.length; i++) {
  for(var j = 0; j < Meat.length; j++){
       combos.push(Fruits[i][0].food + " " + Fruits[i][0].calories + " " + Meat[j][0].food + " " + Meat[j][0].calories);
  }
};
console.log(combos);

Answer №4

If you're looking to combine different meals with fruits, a for loop can be helpful

 meals=[[ { "food": "Salmon", "calories": 250 } ], [ { "food": "Broccoli", "calories": 50 } ]] 
fruits=[[ { "food": "Turkey", "calories": 300 } ], [ { "food": "Pasta", "calories": 400 } ]]
result=[]
for(let x = 0 ;x < meals.length; x++){
for(let y = 0;y <fruits.length; y++){
combo=[meals[x][0].food,meals[x][0].calories,fruits[y][0].food,fruits[y][0].calories]
 result.push(combo)
      }
    }
console.log(result)

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

Issue with Bootstrap 3 dropdown not receiving updates

My goal is to dynamically populate a bootstrap 3 dropdown menu from a MySQL database. Everything works perfectly the first time I load the data. However, when I add more rows to the database, they do not automatically show up in the dropdown. Only after ...

Guide on setting up ShareThis on a Vue.js project

I attempted to include this code in the public index.html file: <script type='text/javascript' src='https://platform-api.sharethis.com/js/sharethis.js#property=5f4e15b2e56e550012ae1e77&product=inline-share-buttons' async='a ...

Techniques for extracting a specific section of a string in Javascript

On another web page, I am extracting a specific string. My goal is to store that string in a variable after a specific point. For example: #stringexample var variable; I need the variable to only include "stringexample" without the # symbol. How can I a ...

Arranging an array based on dual criteria

I am currently working on developing a golf livescore leaderboard and have encountered an issue. I aim to sort the array based on the lowest points, prioritizing players with the same points by the hole they are on. The initial structure of my array is as ...

AngularJS showing up as normal text

I can't seem to get angular JS working properly on my website. It keeps displaying as plain text in the browser and doesn't receive any information from the app2.js. I've double-checked all the dependencies and their locations in my code, so ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...

Employing Ajax long-polling to dynamically refresh content on my webpage by fetching data from an external API

I am using an ajax long polling script (function poll(){ $.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn'); ?>", success: function(data){ //Update your dashboard gauge console.log(data.status); //Data is gett ...

augmentable form that can be expanded flexibly

Perhaps I'm missing something really simple here, but I just can't seem to figure this out. I'm attempting to create a form that can dynamically extend. The issue I'm facing is that I can't get this particular code to function: & ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

The TypeScript error message states that the element type 'Modal.Header' specified in the JSX does not contain any construct or call signatures

Currently, I am delving into TypeScript and React development. In my project, I have been utilizing rsuite for its graphical components with great success. However, I recently encountered an issue while attempting to implement a modal dialog using the Moda ...

Is it possible for certain text within a textbox to activate a jQuery event?

In the development of my MVC ASP.Net application, there is a requirement for users to fill out a form. Specifically, there is a text box where users must input the duration of their current employment. If the user indicates less than three years, an additi ...

How to access the index number of a specific element in an array of

I am seeking to determine if the index number of a given string is divisible by 2. Here is my approach: The initial string provided is 0BCB7A0D87AD101B500B. The objective is to eliminate all instances of "0" characters from the string, but solely when th ...

Step-by-step guide on how to import the socket.io npm package in Node.js

let socket = new Server(); import Server from 'socket.io'; Error: Module 'socket.io' does not have a default export ...

Accessing data from a Vue component externally

Utilizing Vue loaded from a script (not a CLI) in a file named admin.js, I have multiple components that interact with each other by emitting events. No Vuex is used in this setup. Additionally, there is another file called socket which creates a websocket ...

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

`Can you please explain how to retrieve the current state in React?`

PROGRAMMING ISSUE: initializeState: function() { return { title: "", description: "" } }, submitForm: function() { var newTask = { title: this.state.title, description: this.state. ...

I am looking to efficiently sort and structure information from a CSV file using PHP

I am in possession of a csv file containing my vehicle inventory and I am seeking guidance on how to arrange this inventory based on the duration for which I have owned each vehicle. My desired output is as follows - 30 cars 0-30 days old 25 cars 31-60 ...

Is it possible for the Redux state to become unsynchronized?

const SortingFunction = ({ dataState, updateState }) => { const handleClick = () => { const newState = JSON.parse(JSON.stringify(dataState)) // Make necessary updates to the new state based on the current dataState updateState(newStat ...

Struggling to implement my reusable React component within a React Bootstrap modal

I have developed a reusable textarea React component: import React from 'react'; import '../form-input/form-input.styles.scss'; const TextAreaComponent = ({ handleChange, label, ...otherProps }) => ( <div className="group"> ...

Ways to mandate adjusting an option in <select> tag

Using the code $('select').change(function(){alert('changed');});, I am able to trigger an alert every time the option is changed. However, I also need to trigger the alert when the default option, which is the first one in the list, is ...