从Javascript中的数组值生成有效输出

时间:2014-12-23 16:45:12

标签: javascript jquery algorithm

也许这不是一个正确的问题,但我需要一个建议,因为我坚持这个。我有这段代码:

$(document).ready(function(){
  var i = 0, j = 0, 
      manufacturerIds = [1,2,3,4,5,6,7],
      countryIds = [1,2,3,4,5,6,7,8,9,10],
      result = [];

  for (i; i < manufacturerIds.length; i++) {
    for (j; j < countryIds.length; j++) {
       result.push({
         i: {
             idMan: manufacturerIds[i],
             idCtr: [] // stuck on this point, don't know 
                       // where to go from here and don't know 
                       // if I'm doing things right
         }
       });
    }
  }   
});

我正在尝试返回这样的输出:

[
  {
    "0": {
      "idMan": 1,
      "idCtr": [
        1,
        2,
        3,
        4,
        5
      ]
    },
    "1": {
      "idMan": 2,
      "idCtr": [
        1,
        2,
        3,
        4,
        5
      ]
    },
    "2": {
      "idMan": 3,
      "idCtr": [
        1,
        2,
        3,
        4,
        5
      ]
    }
  }
]

有人可以给我一些建议吗?还是帮忙?

注意:我不确定这是正确的还是最好的方法,但我正在尝试构建某种结构,我可以区分对象|数组上的每个项目,为什么?因为我需要添加新元素。例如,此输出也是有效的:

[
  {
    "0": {
      "idMan": 1,
      "idCtr": [
        1,
        2
      ]
    },
    "1": {
      "idMan": 1,
      "idCtr": [
        1,
        4,
        5
      ]
    },
    "2": {
      "idMan": 1,
      "idCtr": [
        3
      ]
    }
  }
]

然后我认为这很容易添加新的idCtr吗?访问someVar[X].idCtr.push(newVal);。顺便说一句,我写了一些var例子,但事实是这些价值观是动态的,只是让你了解我怀疑的理念的起点

2 个答案:

答案 0 :(得分:2)

我相信这更像是你想要的

 var i = 0,
     j = 0,
     manufacturerIds = [1, 2, 3, 4, 5, 6, 7],
     countryIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
     result = [];

 for (i; i < manufacturerIds.length; i++) {
     /* create basic object*/
     var item = {};
     item[i] = {idMan: manufacturerIds[i],idCtr: []};
     /* now push country Ids*/
     for (var j=0;; j < countryIds.length; j++) {
         item[i].idCtr.push(countryIds[j]);
     }
      /* finished creating object*/
     result.push(item);
 }

DEMO

答案 1 :(得分:1)

您可以使用JSON.stringify()将结果转换为JSON。 i: {}还有另一个问题是尝试这样的事情:

$(document).ready(function(){
  var i = 0, j = 0, 
      manufacturerIds = [1,2,3,4,5,6,7],
      countryIds = [1,2,3,4,5,6,7,8,9,10],
      result = [];

  for (i; i < manufacturerIds.length; i++) {
    var obj = {};
    obj[i] = { idMan: manufacturerIds[i], idCtr: [] };

    for (j; j < countryIds.length; j++) {
       obj[i].idCtr.push(countryIds[j]);           
    }
    result.push(obj);
  }   
  var data = JSON.stringify(result);
});