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

标签 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 示例,但事实是这些值是动态的,只是让您了解我的疑问背后的想法的起点

最佳答案

我相信这更符合您的要求

 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

关于javascript - 从 Javascript 中的数组值生成有效输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27624544/

相关文章:

c# - 将对象从 Controller 传递给 JavaScript JQuery

javascript - 使用或不使用 string.slice 对字符串中的字符进行计数

javascript - 如何每 x 秒更改数组中 <li> 的内容?

javascript - 用 jQuery 替换字段

javascript - 使用多个 .each 函数将字符串获取到数组

javascript - 如果没有可用日期,jquery html日历不会从数组中选择日期

javascript - 太多递归 - 单选按钮 - jquery

algorithm - 使用 union-find 对角线连接的连接组件标记

algorithm - 小于比较算法的频率

c++ - 如何使用 STL 算法查找 2D 数组中列值的最大值和最小值