Iterating through JavaScript objects using the foreach method

I'm having difficulty with a JavaScript algorithm. I am working with Vue as my framework and state management tool. I have an object that needs to be 'calculated' as variants.

For instance, I have 3 objects with some values as arrays, like this:

"attributes":[
   {
      "title":{
         "text":"Size",
         "value":"1"
      },
      "values":[
         "M",
         "L",
         "X"
      ]
   },
   {
      "title":{
         "text":"Color",
         "value":"2"
      },
      "values":[
         "Red",
         "Green",
         "Black"
      ]
   },
   {
      "title":{
         "text":"Material"
      },
      "values":[
         "Cotton",
      ]
   }
]

Therefore, the state for this is obviously attributes. What I need to accomplish is to iterate through each attribute value and create a variant for every possible combination, then log them to the console. For example:

M/Red/Cotton, L/Red/Cotton, X/Red/Cotton, M/Green/Cotton, L/Green/Cotton, X/Green/Cotton, M/Black/Cotton, L/Black/Cotton, X/Black/Cotton

I've started a function that only iterates through attributes, so now I need to iterate through values and generate those codes mentioned above, but I'm not sure how to proceed. This is what I have so far:

addVariant: function (text) {
          this.attributes.forEach(element => console.log(element));
        },

Answer №1

It seems like you're interested in generating the Cartesian product of multiple arrays in JavaScript.

For your specific situation, the code snippet below may be precisely what you need:

addVariant: function (text) {
    let cartesian = (...arrays) => arrays.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())), []);
    
    let values = this.attributes.map(attr => attr.values);
    let combinations = cartesian(...values).map(val => val.join('/'));
    console.log(combinations);
},

Answer №2

You can utilize the combination of array#reduce, array#map, and array#flatMap to create a cartesian product of various values.

const attributes = [ { "title":{ "text":"Size", "value":"1" }, "values":[ "M", "L", "X" ] }, { "title":{ "text":"Color", "value":"2" }, "values":[ "Red", "Green", "Black" ] }, { "title":{ "text":"Material" }, "values":[ "Cotton", ] } ],
    result = attributes.reduce((r, o, i) => {
      const array = o.values.map(v => v);
      return i ? array.flatMap(v => r.map(w => (w + '\\' + v))): array;
    },[]);
console.log(result.join());
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

It seems like you are interested in creating combinations of attribute values, correct? I came across a solution for generating combinations using arrays in JavaScript. Although I don't fully understand how it works, I simply copied the code provided.

Returning to your query, my approach would involve creating an array containing all attribute values like this:

parts = attributes.map(attribute => attribute.values)

If you apply the code from the aforementioned answer, you should obtain the desired result:

parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

Your addVariant function could be structured as follows:

addVariant: function (text) {
  const parts = this.attributes.map(attribute => attribute.values);
  const combinations = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
  console.log(combinations)
},

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

Tips for updating the selected value in Vue dynamically

I am currently working on a feature where the months change dynamically based on the selection made using Vue. You can view the code snippet in the link provided below. <div id="app"> <span class="selectboxWrap"> < ...

Issue: [AppRoutes] is not recognized as a valid <Route> component

Currently diving into React-Router with guidance from this helpful tutorial: https://blog.logrocket.com/complete-guide-authentication-with-react-router-v6/ Here's a snippet from my App.jsx: import { Route, createBrowserRouter, createRoutesFromE ...

The jQuery function does not accurately represent the class change made by another event

When hovering over a class anchor, an alert will display the title value. If the anchor has a nohover class, a nopop class will be added to prevent the alert. This ensures that the alert only appears when hovering over the class anchor without the nopop cl ...

The IDs and classes of HTML elements

I have two different implementations of a livechat script. On my sandbox site, the livechat is fixed to the bottom right of the page and scrolls with the window. However, on my live site (where this specific code comes from), it is attached to the footer. ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...

In JavaScript, filter out and return only the parent objects that have a specific property

Let's consider the structure of an object as shown below: var Obj = { a: { name: 'X', age: 'Y', other: { job: 'P', ...

Utilizing Local Storage in Vuex Store with Vue.js

I have been working with localStorage for storing and retrieving items in my JavaScript code housed within a .vue file. However, I am now looking to find a way to transfer this stored data into my Vuex store, specifically within the mutations section locat ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Determine the state of the checkbox based on the information retrieved from the database

I am attempting to dynamically check or uncheck a checkbox based on data retrieved from a MySQL database. I am using the Nusoap webservice/webclient to fetch the data, which can have a value of either 1 or 0. Below is my current code: <input name="che ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

How to Perform a Method Call or Array Iteration in JSX within HTML

Encountering a new issue that I haven't faced before, this is my first time working on something like this and finding a solution is proving to be tricky. Currently, I'm using SendGrid to send an HTML email through a POST request in express on N ...

Troubles with setting up slash commands in discord.js v13

I am encountering an issue while trying to deploy a slash command. The error message DiscordAPIError[50035] is displayed, stating "Invalid Form Body guild_id[NUMBER_TYPE_COERCE]: Value \"undefined\" is not snowflake." const path = require('n ...

default radio option with pre-selected value

Below is a radio option list, but I'm having trouble getting the desired default selection on first render: <label class="radio normalFontWeight"> <input type="radio" name="Criteria" data-ng-value="EVERYONE_REVIEWED" data-ng- ...

Alter the views of a bootstrap date picker in real-time

Is there a way to dynamically change the date picker's view based on different button selections? For example, I have buttons for month, year, and day. Here is what I am trying to achieve: When the month button is selected: I want the date picker ...

Issue with Three.js Raycaster failing to intersect with a custom vertex shader

I'm currently working on implementing a particle system using a dedicated Vertex shader. I have provided a code example for reference: https://jsfiddle.net/dthevenin/7arntcog/ My approach involves utilizing a Raycaster for mouse picking to enable int ...

Error encountered: The function 'showErrorMessage' is not exported from the file '../helpers/alerts'

Within the directory ../helpers/alerts, there is a file called alerts.js const displaySuccessMessage = (success) => { <div className="alert alert-success">{success}</div> } const displayErrorMessage = (error) => { <di ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

Unable to display objects in the console window debugger for debugging purposes

When attempting to print the objects in the console window using the code below, I am receiving an "Undefined" error message. Any advice on how to resolve this issue? var details = [ { name:"Anita", age:"20" },{ name: "H ...

What is the best way to conceal a menu after clicking on #links (links leading to sections on the same page)?

How can I hide my hamburger menu when any of the #links (same page links) are clicked or when someone clicks outside the menu area? I believe I need to modify my JS script, but I'm not sure which part needs changing. I am completely new to JavaScript. ...

Leveraging random attributes in Next.js without encountering the "server/client mismatch" issue

Is there a way to generate unique IDs for form inputs dynamically, in order to avoid conflicts with other elements that share the same ID? If multiple login forms are present on a single page, each with an 'email' field, setting the id property b ...