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

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);
    }
  • 写回答

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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?