Home > database >  Find combination of nested JSON keys
Find combination of nested JSON keys

Time:12-29

I am having some trouble solving this issue without using nested for-loops. I would like to do it using recursion.

Given the following object:

{
  "Color": {
    "Black": [],
    "White": []
  },
  "Effect": {
    "30W": [],
    "40W": [],
    "60W": []
  }
}

The code should compute each combination of Color and Effect and add a number in the list such that the following is produced:

{
  "Color": {
    "Black": [
      1,
      2,
      3
    ],
    "White": [
      4,
      5,
      6
    ]
  },
  "Effect": {
    "30W": [
      1,
      4
    ],
    "40W": [
      2,
      5
    ],
    "60W": [
      3,
      6
    ]
  }
}

My attempt is as follows:

const func = (object, entries) => {
    for (let prop in object) {
        let counter = 0;
        const objLength = Object.keys(object[prop]).length;
        for (let key in object[prop]) {
            console.log(key   counter)
            for (let i = 0; i < entries.length / objLength; i  ) {
                object[prop][key].push(entries[counter]);
                counter  ;
            }
        }
    }

    return object;
}

However, this does not return the desired output. I think it is because of the inner-most for loop condition.

CodePudding user response:

The best way to handle this is to create your JavaScript object and convert it to a string.

// creating your object with attributes.  Objects in objects or whatever you
// need
 var obj = new Object();
   obj.name = "Dale";
   obj.age  = 30;
   obj.married = true;

   dataToAdd.forEach(function(item, index) {
     item.married = false;
   })

// Then convert it to a string using the following code

var jsonString= JSON.stringify(obj);
console.log(jsonString);

CodePudding user response:

I solved the question by considering the space of each attribute key. Then it is just a matter of finding the cartesian, and adding values accordingly:

const cartesian =(...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));

function diy(jsonObj, counter) {
    let permObj = []
    let keys = Object.keys(jsonObj)

    keys.forEach(key => {
        permObj.push(Object.keys(jsonObj[key]))
    });

    permObj = cartesian(...permObj)

    for(let i = 0; i < keys.length; i  ) {
        for(let j = 0; j < permObj.length; j  ) {
            jsonObj[keys[i]][permObj[j][i]].push(j   counter);
        }
    }

    return jsonObj;
}
  • Related