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

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入