Priya
Priya

Reputation: 1481

javascript: Array looping

I have two an object which contains 2 arrays. I want to create loop in such a way that each element of first array gets concated to each element of second array.

{'array1':['a','b'],'array2':['1','2']}

it should create new array

['a,1':{'prop1':""},'a,2':{'prop1':""},'b,1':{'prop1':""}, 'b,2':{'prop1':""}]

How to do this in javascript.

Upvotes: -1

Views: 72

Answers (2)

scmrz5
scmrz5

Reputation: 21

Here's a function that builds on @dev-null's solution. This restructures the object in the way you want, but isn't dependent on the keys' names or the number of arrays in the object. It should work with an input object of any length, as long as its structured in the same way. Also, I'm sure there's a way to optimize this, but it seems to be fast enough for this example.

var input = {
    'array1':['a','b'],
    'array2':['1','2', '3'],
    'array3':['x','y', 'z']
};

var output = combineObj(input);
console.log(output);

// In: an object of arrays
// Returns restructured object
function combineObj(obj) {

    var allVals = [];
    var locatoins = [0];
    var output = {};

    var keys = Object.keys(obj).sort();
    var counter = 0;

    // combine each individual array into one big array
    keys.forEach(function(objItem, indx){

        obj[objItem].forEach(function(aryItem){
            allVals.push(aryItem);
            counter++;
        });
        locatoins.push(counter);
    });

    // Used in combination with the locations array to track where a new array begins
    // The purpose of this is so items from the same array in input aren't combined
    var iterator = 1;

    for( i=0; i < allVals.length; i++ ){

        if(i == locatoins[iterator]){
            iterator++;
        }

        for( j = 0; j < allVals.length; j++ ){
            if( j >= locatoins[iterator-1] && j < locatoins[iterator] ){
                continue;
            }
            output[allVals[i] + ', ' + allVals[j]] = { prop1: '' };
        }
    }
    return output;
}

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47127

Your output is not posible, this is not valid syntax: ["abc": {...}] what you want to output is an object like so: {"abc": {..}}

You will need to iterate over both arrays, one outer iteration and one inner iteration:

var input = {'array1':['a','b'],'array2':['1','2']};
var output = {};

// Outer iteration:
// a1 will contain each value from array1 (a, b)
input.array1.forEach(function(a1) {
  // Inner iteration:
  // a2 will contain each value from array2 (1, 2)
  input.array2.forEach(function(a2) {
    // Concatenate the to values (`a,1`, `a,2`, `b,1`, `b,2`) and assign the dummy object:
    output[a1+','+a2] = { prop1: '' };
  });
});

console.log(output); // {"a,1":{"prop1":""},"a,2":{"prop1":""},"b,1":{"prop1":""},"b,2":{"prop1":""}}

Upvotes: 2

Related Questions