Adding an array of objects to a specific key using JavaScript

I'm facing a challenge with adding an array of objects to an existing array of objects using Vue.js. What I'm attempting to accomplish is creating a form repeater within another form repeater. While I was able to successfully implement the first one, the second one is proving to be quite daunting.

I have experimented with splice and push functions, but they are not producing the desired outcome. In the function for the initial form repeater (which is functioning properly), 'parent' is defined as an array in the state.

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

The output currently looks like this:

parent: [
            {
                name: 'My name',
                age: 32,
            }
        ]

Now, what I need is to add a child object to this structure, making it look like:

parent: [
            {
                name: 'My name',
                age: 32,
                child: [
                    {
                        name: 'My children',
                        school: 'Elementary'
                    }
                ]
            }
        ]

I've been trying to achieve this by utilizing the following approach:

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

Despite my efforts, this method hasn't been successful, as it ends up adding a new array of parents and a child object. I also attempted another strategy:

addChildrenSecondTry: function (index) {
            var dd = [];
            dd[index] = {
                    child: {
                      name: '',
                      school: '',
                  }
                };

            this.form.packages.splice([index], 0, dd);

        }

Unfortunately, neither of these approaches has yielded the desired results. I explored options such as push while passing a key from a parent, but encountered errors stating that push is not a function.

If you'd like to further investigate my issue, feel free to visit this CODEPEN example I created to provide more clarity on my situation.

Answer №1

Experiment with replacing the existing keys with a new one (child) at the specified position

addChildren: function (position) {
            this.form.parent.splice(position, 1, {
                ...this.form.parent[position],
                child: {
                    name: '',
                    school: '',
                }
            });
        },

Answer №2

To incorporate the array/object into the parent object directly, I utilized a ternary operator to ascertain the existence of the 'child' key. If the key is present, the object is added to it. Alternatively, if the key doesn't exist, a new one is created with the object inside an array.

function addChildren(index) { this.form.parent[index].child =
this.form.parent[index].child ? this.form.parent[index].child.push({name: '',
school: '',}) : [ {name: '', school: '',} ]; } }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

I'm experiencing some issues with the JavaScript setTimeout function - can anyone help troubleshoot

in my quest to find a way to hide the notificationBar without the use of a button and using XX.hide() oncomplete, I stumbled upon a javascript snippet <script type="text/javascript> jQuery(function() { bar.show(); setT ...

Index is bound to data using a specific syntax for data binding

Having trouble with a syntax issue that is likely simple. I am attempting to replace the '1' in 'play1' with the v-for index. <tr v-for="index in 5"> <td>{{player1.round1['play' + index]}}</td> <td> ...

Having trouble accessing the div element inserted by the Angular application

I've encountered an issue while trying to access a div that is injected into the DOM by an Angular app on the page. Below is the script I have placed at the end of the HTML page: $(document).ready(function () { var targetNode = document.querySelect ...

Effortlessly sending multiple values from text fields using jQuery

i am using jQuery to fetch all values from text fields with the same field name. $('input[name^="StudentName"]').each(function() { StudentName += $(this).val(); alert(StudentName); }); when I alert, all the values are displayed as one s ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...

Adding an item to an array in Angular 2 using JavaScript!

In my Angular2 form, I have a field that consists of an array of objects. I've successfully created a table with a Delete Row button for each row and an Add Row button using the push() and slice() methods in JavaScript. However, there's a major ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...

Tips for wrapping a div around its floated children

I'm currently developing a website for an online shopping cart and working on making the search results responsive. I am aiming to display as many items as possible across the screen (usually 3) when viewed on any device with a resolution lower than t ...

Sending information from AngularJS to nodeJs/Sequelize

I am currently in the process of developing an e-commerce website using Node.js/Sequelize and AngularJS. For my project, I have organized it into 2 main folders: Client (which houses AngularJS starter files) https://i.stack.imgur.com/0vzsF.png Server ...

Obtain a report using a variety of different conditions

My database has a table with the following fields: TPI CLICKS IMPRESSION CLASSIFY I am looking to retrieve 3 specific results: 1) Calculate SUM(CLICKS)/SUM(IMPRESSION) * 100 GROUPED BY TPI 2) Calculate SUM(IMPRESSION) WHERE CLASSIFY = "XYZ" GROUPED BY ...

Angular.js - organizing a list of items and preserving the outcome

Here is a compilation of randomly arranged items: <ul class="one" drag-drop="page.items"> <li ng-repeat='item in page.items|orderBy:page.random as result'> <img ng-src="http://placecage.com/{{item.id*100}}/{{item.id*100}}"& ...

Using Javascript to upload an image and show it in a small display

Hey there, I have a functioning JavaScript code that loads an image uploaded by the user onto the HTML page. However, the issue is that the image doesn't have a set maximum height or width, causing buttons on the page to move out of view and become in ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

Eliminate elements from an array using a specific key for filtering

My Array is called MainArray MainArray=[{ {First Name: "First Name"}, {Last Name: "Contact"}, {Last Name: "Contact"} ] I am trying to trim the key-value pair from this array like this: if (key == 'First Name') { del ...

The Axios post request was met with a 400 error, indicating a bad request

When testing an API using Postman, I encountered an issue when trying to write a request with axios. The original request in Postman was successful and looked like this: https://i.sstatic.net/71EWL.png In my attempt to recreate the request in javascript ...

Is there any issue that you can spot with this js / jQuery code?

Presented below is a script that prompts the user to confirm clicking a button based on a system setting. The system setting is saved in a hidden field established from the code-behind. Markup: <asp:HiddenField ID="hfConfirmOnApproval" runat="server" ...

JavaScript decimal validation not functioning as intended

Hey everyone! I've created a script that restricts textboxes to allow only decimal numbers. Take a look at the code snippet below: function onlyDecimal(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) ...

Error: No package.json file found after publishing npm package with ENOLOCAL

Ecosystem using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335d435e73051d021d03">[email protected]</a> using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a8a9a2a386b0fee8f7f7e ...