Traverse through deeply nested objects and combine into a single string using the Lodash library

Currently, I am utilizing Lodash to streamline object manipulation. Within my object, there are three nested objects that I would like to iterate through, combining all of their respective children in various combinations. The goal is to include only one item from each list.

Here is a representation of my object:

{
  "list_1": {
    "1": ".cat-3",
    "2": ".cat-5",
    "3": ".cat-7"
  },
  "list_2": {
    "1": ".eyes-blue",
    "3": ".eyes-brown"
  },
  "list_3": {
    "1": ".jazz",
    "2": ".commercial",
    "3": ".hip-hop"
  }
}

The desired output should look something like this:

.cat-3.eyes-blue.jazz
.cat-3.eyes-blue.commercial
.cat-3.eyes-blue.hip-hop

The sequence of the values is not significant, as long as only one value from each list_ object is utilized in the string. Therefore, variations such as these are acceptable:

.eyes-blue.jazz.cat-3
.eyes-blue.cat-3.commercial
.hip-hop.eyes-blue.cat-3

Below are additional examples:

.cat-3.eyes-brown.jazz
.cat-5.eyes-brown.hip-hop
.cat-7.eyes-blue.hip-hop

Answer №1

Arrange the property values in the form of an array containing arrays:

var arrayOfArrays = [];

_.each(obj, function(item, key) {
  var itemValues = [];
  _.each(item, function(innerItem, innerKey) {
    itemValues.push(innerItem);
  });
  arrayOfArrays.push(itemValues);
});

Create the suffle() function following this guide:

Create a function to retrieve a random element from an array:

function getRandomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

Create a function to select random elements from an array of arrays and concatenate them into a string:

function getRandomCombination(arrayOfArrays) {
  var result = ""; 
  _.each(arrayOfArrays, function(innerArray) {
    result += getRandomElement(innerArray);
  })
  return result;
}

Now you can get the desired output by executing something like:

getRandomCombination(suffle(arrayOfArrays));

or, if you prefer to keep arrayOfArrays unchanged:

getRandomCombination(suffle(arrayOfArrays.slice(0)));

Answer №2

Utilizing the zip function provided by lodash, you can group elements into arrays where the first array contains the first elements from each given array, the second array contains the second elements, and so on.

_.zip(['alice', 'bob'], [25, 35], [false, true]);
// → [['alice', 25, false], ['bob', 35, true]]

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

Problem with jQuery's .prepend method being called twice on list items

Looking to enhance the appearance of a list by adding some icons before the anchor links within each list item. <ul class="submenu-children"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> ...

Struggling with deploying Next.js on Vercel

Encountered an issue while trying to deploy a project on Vercel. The error message is as follows: fileName: comps/Navbar.js imported as import Navbar from "./Navbar"; 16:36:51 ModuleNotFoundError: Module not found: Error: Can't reso ...

Error: react-router v4 - browserHistory is not defined

I'm diving into the world of creating my very first React app within Electron (also my first experience with Electron). I have two routes that need to navigate from one to another. Here's the code snippet I am using: Root ReactDOM.render( < ...

What is the best way to create height segments from a cylinder in three.js?

My current project involves a cylinder that is divided into multiple height segments, with the number of segments depending on the specific data. Each height segment contains a value that I want to use for extruding the entire circle at that particular hei ...

What are the steps to create a "load more" button that displays additional rows?

Struggling to get the code right for my webpage. I have a layout with 6 rows, each containing 3 columns filled with images. However, when I click on the "load more" button, nothing happens. I've attempted to modify the jQuery code from .slice(0, 3) t ...

Here's a guide on executing both GET and POST requests using a single form

Currently, I am developing a web application which involves using a GET request to display checkboxes in a form. The selected data from the checkboxes needs to be sent back to the server using a POST request. However, I'm facing an issue with performi ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

How can jQuery determine the amount of line breaks within a div element?

My div wrap size is a percentage of the screen width, containing multiple .item divs that break into new lines as the window size decreases. I attempted to calculate the total number of boxes that could fit based on their widths compared to the container ...

To trigger a pop-up window displaying a link upon clicking the submit button

I am attempting to create a popup box that displays an application accepted message and a link back to the home page upon clicking the submit button. However, the .popup box is not appearing after validation. This is the content that should be displayed w ...

Javascript - combining properties using "concatenation"

I'm currently pulling data from JSON for a three.js scene. My goal now is to transform data such as "position.x : 1" into object[ position ] [ x ] = 1. The syntax object [ key ] = value isn't effective in this case. This would result in object[ ...

What are some Ruby array functions that can be used to find items based on an object's attribute?

If I have a Ruby class called Flight, which includes an attr_accessor :key, and there's an array of instances of this class like so: flights = [flight1, flight2, flight3]. Now, let's say I have a "target key" such as "2jf345", and I want to find ...

I am experiencing an issue where my observable value gets reset after setting it in KnockoutJS + Chosen

Currently, I am in the process of creating a user interface for building charts. Users have the ability to select fields from a database in order to construct a graph. Additionally, these graphs come with a refresh interval dropdown feature. Everything fu ...

Implementing modifications to all HTML elements simultaneously

In my HTML document, there are around 80 small boxes arranged in a grid layout. Each box contains unique text but follows the same structure with three values: name, email, and mobile number. I need to switch the positions of the email and mobile number v ...

Is there a way to customize the color of the HR element in a Material-UI Select Field?

https://i.stack.imgur.com/DYeX7.png https://i.stack.imgur.com/CN0T6.png Hi there, I am currently working on a website and using a Select Field component from Material-UI. I am faced with the challenge of customizing the style to change the default light ...

Utilizing JavaScript for the removal or hiding of span elements with specific class attributes

I am currently working on a software project that involves compiling HTML fragments and then exporting them to Microsoft Word. My goal is to create a script that will cycle through these compiled fragments and remove specific tags that have a particular CS ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Exploring a Discord.js collection: tips for accessing and manipulating objects within an array in the collection

I have a discord.js Collection that contains information about dispatcher and queue objects. Here is the structure: Collection(1) [Map] { '403547647215927306' => { dispatcher: StreamDispatcher { _writableState: [WritableState], ...

Having successfully configured and published Google Tag Manager, unfortunately, I am encountering difficulties in displaying the tag on the website

After setting up my GTM account and creating containers, tags, etc., I encountered an issue. Even after publishing my container and creating a version, when I checked my website, all the code was hidden within a div tag with display none and visibility hid ...

Tips for manipulating bits 52-32 within Javascript code, without utilizing string methods

Here is my functional prototype code that is currently operational: function int2str(int, bits) { const str = int.toString(2); var ret = ''; for (var i = 0; i < (bits - str.length); ++i) { ret += '0'; } re ...

What is the best way to use element.appendChild to generate a link?

I am currently utilizing the following snippet of Javascript to extract information from the current webpage using a browser extension. I have only included a portion of the code that is relevant, as the full script is quite lengthy. The code works perfect ...