简体   繁体   English

将项目添加到数组中的子数组

[英]Add Item to Sub-Array in an array

I have an array我有一个数组

vm.prdGroups = [{
  type_id: '1',
  group_name: '',
  is_required: false,
  position: 0,
  options: {
    item_name: '',
    item_price: '',
    position: 0

  }
}];

How do I add a new array to the options key, to have something like this如何向 options 键添加一个新数组,以获得类似的内容

vm.prdGroups = [{
  type_id: '1',
  group_name: '',
  is_required: false,
  position: 0,
  options: {
    item_name: '',
    item_price: '',
    position: 0
  },
  {
    item_name: '',
    item_price: '',
    position: 0
  }
}];

First thing is your vm.prdGroups.options is not a array.首先是你的 vm.prdGroups.options 不是一个数组。 You need to make it a array and then push new values to it.您需要将其设为数组,然后向其推送新值。

 let vm={}; vm.prdGroups = [{ type_id: '1', group_name: '', is_required: false, position: 0, options: { item_name: '', item_price: '', position: 0 } }]; let temp= vm.prdGroups[0].options; vm.prdGroups[0].options = [] vm.prdGroups[0].options.push(temp,'some other object'); console.log(vm.prdGroups);

I realized my options wasn't actually an array, so I couldn't possibly push to it, I made it an array, and it made the task doable我意识到我的选项实际上不是一个数组,所以我不可能送到它,我把它变成了一个数组,它使任务变得可行

  vm.prdGroups = [
                {
                    type_id: 1,
                    group_name: '',
                    is_required: false,
                    position: 0,
                    options: [{
                        item_name: '',
                        item_price: '',
                        position: 0
                    }]
                }
            ];

And I could push to the array inside an array with the use of index, so the method to push was this我可以使用索引推送到数组内的数组,所以推送的方法是这样的

 vm.addPrdItem = function (index) {
            console.log(index);
            var itemLength = vm.prodAttribs.product_groups[index].options.length - 1;
            vm.productItems = {
                item_name: '',
                item_price: '',
                position: itemLength + 1
            };
            vm.product_groups[index].options.push(vm.productItems);
        }

Thanks to all who answered, appreciate.感谢所有回答的人,不胜感激。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM