将数组合并到对象以及对象合并到数组

Merge arrays to object and object to array

本文关键字:对象 合并 数组      更新时间:2023-09-26

所以我在这里有一个棘手的问题:

我从这个函数中获得了 5x2 数组

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

对于这 5 个重复中的每一个,我想将两个数组放入这样的对象中

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

这些对象现在应该放在数组中。所以最后我想将 5 个数组(从截取的第一个代码开始)放入一个数组中,如下所示

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

]

我知道这有点复杂...

我所知,你想做这样的事情

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

我不确定我是否正确理解了您的要求,但我认为这就是您要找的

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

这应该有效

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