Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object value being over written by last value on the Loop

I have following input data:

{
   'a': [1, 2, 3],
   'b': ['x', 'y', 'z'],
   'c': ['a', 'b', 'c'],
}

I am trying to change above input data into following data structure:

{ 
  '0': { a: 1, b: 'x', c: 'a' },
  '1': { a: 2, b: 'y', c: 'b' },
  '2': { a: 3, b: 'z', c: 'c' }
} 

My Javascript Code is:

let parentDataset = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
} 

let children = {};
let parent = {};

for (let key in parentDataset) {

  let i = 0;
  for (let value of parentDataset[key]) {        
    children[key] = value;
    parent[i] = children;
    i++;
  }
}

console.log('parent', parent);

But I am getting following output where last value is over writing previous two values as below:

{ 
  '0': { a: 3, b: 'z', c: 'c' },
  '1': { a: 3, b: 'z', c: 'c' },
  '2': { a: 3, b: 'z', c: 'c' }
}

Any solution and explanation would be much appreciated!

like image 201
Jant Avatar asked Dec 13 '25 06:12

Jant


2 Answers

After getting the list of keys, you can Array#reduce one of the arrays to a series of objects, and populate them using Array#forEach and Object#assign:

const obj = {
   'a': [1, 2, 3],
   'b': ['x', 'y', 'z'],
   'c': ['a', 'b', 'c'],
};

const keys = Object.keys(obj);

const result = obj[keys[0]].reduce((r, _, i) => {
  const o = r[i] = {};
  
  keys.forEach((key) => Object.assign(o, { [key]: obj[key][i] }));

  return r;
}, {});

console.log(result);

And here is a working version of your code:

const parentDataset = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
} 

const parent = {};

for (const key in parentDataset) {
  let i = 0;
  
  for (const value of parentDataset[key]) {        
    !parent[i] && (parent[i] = {}); // create a new object if one is needed
    parent[i][key] = value; // add the key and value to the object
    i++;
  }
}

console.log('parent', parent);
like image 190
Ori Drori Avatar answered Dec 14 '25 21:12

Ori Drori


Another solution would be to reduce object's values. For example:

const data = {
  'a': [1, 2, 3],
  'b': ['x', 'y', 'z'],
  'c': ['a', 'b', 'c'],
}

const result = Object.values(data).reduce((acc, subarr, idx, arr) => {
  return { ...acc, [idx]: arr.map(sub => sub[idx]) }
}, {})
like image 25
madox2 Avatar answered Dec 14 '25 20:12

madox2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!