llaid
llaid

Reputation: 85

Modify an object to a new Array in Javascript

sorry, i m a beginner in javascript. Can someone explain me how to modify this Object

{toto:[12,13,15],titi:[45,12,34]}

to this Array

 newArray =  [
 {
  toto:12,
  titi:45
 },{
  toto:13,
  titi:12
 },{
  toto:15,
  titi:34}
]

Also, what the solution if the toto and titi doesn't have the same lenght Thanks for support!

Upvotes: 0

Views: 59

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386550

A more generic approach

var object = { toto: [12, 13, 15], titi: [45, 12, 34] },
    newArray = function (o) {
        var keys = Object.keys(o),
            l = keys.reduce(function (r, a) { return Math.max(r, o[a].length); }, 0),
            i = 0,
            t,
            result = [];

        while (i < l) {
            t = {};
            keys.forEach(function (k) { t[k] = o[k][i]; });
            result.push(t);
            i++;
        }
        return result;
    }(object);

document.write('<pre>' + JSON.stringify(newArray, 0, 4) + '</pre>');

Upvotes: 1

Shaun
Shaun

Reputation: 2052

Here's how I did it. In this way, you don't need to know the names of the keys or the size of the array, but it does require a few loops.

obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];

// Find the longest array in your data set
longest = 0;
Object.keys(obj).forEach(function(key) {
  if (obj[key].length > longest) {
    longest = obj[key].length;
  }
});

// Loop through the existing data set to create new objects
for (i = 0; i<longest; i++) {
  newObject = {};
  Object.keys(obj).forEach(function(key) {
    newObject[key] = obj[key][i];
  });
  newArray.push(newObject);
}

console.log(newArray);

plnkr.co demo in the script.js file.

If you want to ignore keys that would have undefined values for uneven loops, you can add a conditional inside the forEach loop that creates a new object:

  Object.keys(obj).forEach(function(key) {
    if (obj[key][i] !== undefined) {
      newObject[key] = obj[key][i];
    }
  });

Upvotes: 1

Rion Williams
Rion Williams

Reputation: 76547

Since the lengths of your inner arrays are equal, you should be able to simply loop through them and add a value from each array (for each iteration) into a new array :

// Your input
var input = {toto:[12,13,15],titi:[45,12,34]};
// An array to store your output
var output = [];

// Since your inner arrays are of equal size, you can loop through them
// as follows
for(var i = 0; i < input.toto.length; i++){
    output.push({ toto: input.toto[i], titi: input.titi[i]});
}

You can see a working example of this here and what the output array looks like below :

enter image description here

Upvotes: 1

u_mulder
u_mulder

Reputation: 54831

Assuming lengths of toto and titi are the same:

Obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];
for (var k in Obj["toto"]) {
    newArray.push({ toto:Obj["toto"][k],titi:Obj["titi"][k] });
}

Upvotes: 1

Related Questions