brighthero
brighthero

Reputation: 135

Merge arrays to object and object to array

So I have little bit of a tricky problem right here:

I'm getting 5x2 arrays from this function

for (var i = 0; i < 5; i++) {
    var name = $('.lesson-space:eq( ' + i + ' ) > .lesson').map(function(){return $(this).data('name');}).get();
    var color = $('.lesson-space:eq( ' + i + ' ) > .lesson').map(function(){return $(this).data('color');}).get();
  };

For each of these 5 repeats I want to put the two arrays into an object like this

     {
        "name": "deutsch",
        "color": "red"
      },
      {
        "name": "mathe",
        "color": "blue"
      },
      {
        "name": "sport",
        "color": "darkblue"
      },
      {
        "name": "franz",
        "color": "yellow"
      }

These objects should be put now into in array. So in the end I would like to have 5 arrays (from the first code snipped) put into one array like this

[
[
    ...
],[
    ...
],[
    ...
],[
    ...
],[
    ...
]

]

I know it's a bit complicated...

Upvotes: 0

Views: 42

Answers (3)

Oleksandr T.
Oleksandr T.

Reputation: 77482

As I understood you want to do something like this

var res  = [],
    data = {}; 

for (var i = 0; i < 5; i++) {

  data = $('.lesson-space:eq( ' + i + ' ) > .lesson').map(function () {
    var name  = $(this).data('name');
    var color = $(this).data('color');

    if (!name || !color) {
      return null;
    }

    return {
      name:  name,
      color: color
    }
  }).get();

  res.push(data);
}

Upvotes: 1

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

I'm not sure I've understood you requirements correctly, however I think this is what you're looking for

var result = [];
for (var i = 0; i < 5; i++) {
    result.push($('.lesson-space:eq('+i+') > .lesson').get().map(function(){
        return {
            name: $(this).data('name'),
            color: $(this).data('name')
        };
    }));
}

console.log(result);

Upvotes: 1

Mohamed El Alouani
Mohamed El Alouani

Reputation: 66

This should work

var mainArray = [];

for (i = 0; i < name.length; i++) {
    var o = {};
    o.name = name[i];
    o.color = color[i];
    mainArray.push([o])
}

Upvotes: 0

Related Questions