简体   繁体   中英

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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