简体   繁体   中英

JavaScript add object to existing object

I have some problems adding object to object, or to be more specific array of objects. I'm using vue and I need to add some objects to specific array, and need to specify a key, but push function is not working as needed. So I find a function splice and I'm using it in function like:

addPackageInfo: function (index) {
            this.form.packages.splice(index, 0, {
                info: {
                    country: index,
                    real_price: '',
                    sale_price: '',
                    delivery_price: ''
                }
            });
        },

But it's doing something that I don't need, it will delete other data (objects) and replace it with given one. Is there any way so I can just append that objects?

In your codepen the problem is that you are using the same array for parents and children, so both addParent and addChildren function edit the same array.

addParent: function () {
            this.form.parent.push({
                name: '',
                age: '',
            });
        },

addChildren: function (index) {
          console.log(index);
          this.form.parent.splice([index], 0, {
               child: {
                  name: '',
                  school: '',
               }
          });
        },

I think that what you want is that for each item in parents array there is an array of children. Try out this pen and let me know if I correctly understand your problem

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