0

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...

2
  • underscore or lo-dash would be able to help you achieve this more easily... if you don'd mind the dependency add. Commented Nov 22, 2014 at 15:03
  • also why would you switch back and forth between object and array structure? or do you want to put 5 objects, inside an array, which is inside another array? Commented Nov 22, 2014 at 15:06

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

1 Comment

you have to put .get() at the end :)
0

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])
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.