gosseti gosseti - 1 year ago 139
Javascript Question

Iterate over nested objects and concatenate to string using Lodash

I’m using Lodash to make manipulating objects easier. I have an object with three nested objects inside. I’d like to iterate through these, concatenating all of their respective children together in all possible combinations, whilst only using one per list.

My object looks like this:

"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 output I’d like to get is:


The order isn't crucial. What's crucial is that only one value from each
object is used in the string. So this, for example, would be fine:


And some more examples:


dug dug
Answer Source

Store the values of the property objects as an array of arrays:

var arrayOfArrays = [];

_.each(obj, function(item, key) {
  var itemVals = [];
  _.each(item, function(item2, key2) {

Implement the suffle() function as described here: http://stackoverflow.com/a/2450976/2193416

Implement a function to get a random array element:

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

Implement a function to select random elements from an array of arrays as a concatenated string:

function randomCombination(arrayOfArrays) {
  var output = ""; 
  _.each(arrayOfArrays, function(innerArray) {
    output += randomElement(innerArray);
  return output

Now you can get a desired output by doing something like:


or, if you want to keep arrayOfArrays intact:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download