-1

I've an Object containing data that looks like this,

obj = {
Q1:['val1','val2'],
Q2:['val3','val4','val5'],
Q3:['val8']
}

I was trying to loop over keys and get and first element in each key concate each element in each array, and join them together using , (my object has more keys that this ofc)

So the output should be like

  • val1,val3,val8
  • val2,val4,
  • ,val5,

I tried to loop over keys and getting each value but i think i'm missing something in my loop, as i can't change the key if it found element in each object

These are my trials below.

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    for (let i = 0; i < obj[key].length; i++) {
          console.log(obj[key][i])//This is always looping on the same key but different element          
    }
  }
}

while i want it to be something close to

 for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
          console.log(obj[key][i])         
  }
}
Doom
  • 206
  • 1
  • 4
  • 14
  • would you please clear more about the output description you mentioned? – Shuvojit Saha Jun 24 '20 at 10:35
  • I want to concatenate each element from each array, as i should get val1 concat val3 concat val8 , then i'll make string join between them using , in order to make then val1,val3,val8 .... and whenever it doesn't find a value inside this array (as not all arrays are equal it should put just blank and do a , so it become val2,val4,'' – Doom Jun 24 '20 at 10:39
  • @user120242 this is talking about equal length arrays, but unfortunately this isn't my case – Doom Jun 24 '20 at 10:55
  • Scroll down. To emulate zip it also has to support unequal length arrays. – user120242 Jun 24 '20 at 10:57
  • Or are you talking about [cartesian](https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript)? Your output actually doesn't make sense. – user120242 Jun 24 '20 at 11:02
  • Why do you have `val3,val5` in the output? – adiga Jun 24 '20 at 11:04
  • I'm trying to put my output in this form in-order when i write it to csv file, it should be column row wise, but each complete row, have a value from each column. (if my explanation is not clear please tell me ) so the final goal for me to have an [ [ ] ] , where each array inside the big array, should contain the output as above to be written to csv – Doom Jun 24 '20 at 11:06
  • @AdhamNawito val3 is column 1, val5 is column 3. Those are different columns, and from the same row? – user120242 Jun 24 '20 at 11:06
  • @adiga this was typo mistake, my apology – Doom Jun 24 '20 at 11:07
  • @user120242 yes this is totally what i want to do – Doom Jun 24 '20 at 11:08

3 Answers3

0

My solution uses a deep copy of the object and then a recursive array manipulation via shift():

obj = {
  Q1:['val1','val2'],
  Q2:['val3','val4','val5'],
  Q3:['val8']
}

var resObj = [];

function printByIndex(obj){
  var newObj = JSON.parse(JSON.stringify(obj));
  printByIndexHelper(newObj, 0);
}

function printByIndexHelper(obj, i){
  var flag = false;
  resObj[i] = [];
  Object.keys(obj).forEach(function(key){
    if(obj[key].length > 0){
      resObj[i].push(obj[key].shift());
      if(obj[key].length > 0){
        flag = true;
      }
    }else{
     resObj[i].push(null);
     }
  });
  if(flag){
    printByIndexHelper(obj, i+1);
  }
}

printByIndex(obj);
console.log(resObj);
Greedo
  • 3,438
  • 1
  • 13
  • 28
0

check this same output as u require

 obj = {
    Q1:['val1','val2'],
    Q2:['val3','val4','val5'],
    Q3:['val8']
    }
    
    var keys = Object.keys(obj);
    var stack = [];
    var maxLength = getMaxLength(obj);
    
      for(var k = 0; k < 3;k ++) {
          var arr = [];
        
        for(var i = 0; i<keys.length;i++) {
          const key = keys[i];
          const elements = obj[key];
    
            if(k < elements.length) {
              arr.push(elements[k]);  
            }
        }
    
            console.log(arr+"\n");
        //stack.push(arr);
    }
    
    
    function getMaxLength(jsonObj) {
      var max;
      var jsonKeys = Object.keys(jsonObj);
      for(var key of jsonKeys) {
        const arr = jsonObj[key];
        if (max == null || arr.length > max) {
          max = arr.length;  
        } 
      }
      return max;
    }
0

Maps over arrays and joins string. Math.max to get full length to iterate over. Uses flatMap to filter out unequal length array values.

obj = {
Q1:['val1','val2'],
Q2:['val3','val4','val5'],
Q3:['val8']
}

const o = Object.values(obj)
const len = Math.max(...o.map(({length})=>length))
console.log(
Array(len).fill().map((x,i)=>o.flatMap(q=>q[i]||[]).join(','))
)
user120242
  • 14,918
  • 3
  • 38
  • 52