doujiang2812
2017-03-28 15:10
采纳率: 0%
浏览 51

Laravel - Javascript - 在多维数组中保存所有数量和id

I have the problem to save all product_id's with the related quantitie in a multidimensional array.

I have a laravel foreach loop that gives me every product from a bigger products array.

Every single product has a data-id attribute and an <input type="number"> element to select the quantitie.

Thats how I get all the data-id's and the quantities :

$('.update').on('click', function() {
    var ids = $('.list').map(function () {
        return $(this).data("id");
    }).get();

    var quantities = $('input[type=number]').map(function () {
        return $(this).val();
    }).get();
});

Output of the ids variable: 55,65 Output of the quantities variable: 1,2

My problem is that I need a multidimensinal array that gives me the right product with the related quantitie.

Something like:

var product_data = [
    [0] = "id":55,
          "quantitie":1,
    [1] = "id":65,
          "quantitie":2
];

I wasn't able to get it like I need it. I'm still very new to javascript.

Thanks for any help and sorry for my bad english!


what I tried:

    for (var i = 0; i < ids.length; i++) {
        var product_data = [
            id = ids[i],
            quantitie = quantities[i]
        ];
        alert(product_data);
    }

图片转代码服务由CSDN问答提供 功能建议

我有问题是在多维数组中使用相关的数量保存所有product_id。

我有一个laravel foreach循环,它为我提供了更大产品阵列中的所有产品。

每个产品都有 data-id 属性和&lt; input type =“number”&gt; 元素来选择量子。

这就是我如何获得所有数据ID和数量:

  $('。update')。on('click  ',function(){
 var ids = $('。list')。map(function(){
 return $(this).data(“id”); 
})。get(); \  n 
 var quantity = $('input [type = number]')。map(function(){
 return $(this).val(); 
})。get(); 
});  
   
 
 

输出ids变量:53,55 输出数量变量:1,2

我的问题是 我需要一个multidimensinal数组,给我正确的产品与相关的数量。

类似于:

  var product_data = [
 [0] =“id”:55,
“quantitie”:  1,
 [1] =“id”:65,
“quantitie”:2 
]; 
   
 
 

我无法得到它 就像我需要它一样。 我还是javascript的新手。

感谢您的帮助,抱歉我的英语不好!


我尝试了什么:

  for(var i = 0; i&lt; ids.length;  i ++){
 var product_data = [
 id = ids [i],
 quantitie = quantity [i] 
]; 
 alert(product_data); 
} 
    
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxi7722 2017-03-28 15:19
    已采纳

    You can try combining those two arrays together. There are just two assumptions in that

    1. Both arrays are the same length
    2. Both arrays are correctly sorted

    var ids = ["1", "2"];
    var quantities = [ "30", "40" ];
    
    var res = [];
    ids.forEach(function(id, i) { 
      res.push({ id: id, quantitie: quantities[i] });
    });
    console.log(res);

    </div>
    
    打赏 评论

相关推荐 更多相似问题