Add array as an element within another array

After initializing the data, I have an object structured like this and I am able to push data using the method below:

myObj = {
    1: ["a", "b", "c"],
    2: ["c", "d", "e"],
}

data: {
   types: {}
},

methods: {

  pushValue(key, value) {
      var obj = this.types

      if (obj.hasOwnProperty(key)) {
          var idx = $.inArray(value, obj[key]);
          if (idx == -1) {
             obj[key].push([value]);
          }
      } else {
          this.$set(obj, key, [value]);
      }
  },
}

This current structure functions properly.


However, now I aim for my object to be in this format:

myObj = {
    1: {
        "a": [
           [],[]
        ], 
        "b": [
           [],[]
        ],
       }
 }

I need guidance on how to modify my append function to achieve this new structure.

Answer №1

My interpretation of @senty's goal leads me to explain the functionality as follows:

The method pushValue is designed to accept numbers as keys and characters as values, saving them into this.types. When pushValue is invoked, this.types will create a property with the key storing an object where the value serves as its key, containing an array that may append additional empty arrays if necessary. Ultimately, this.types will resemble myObj.

Thus, the implementation of pushValue should be structured like this:

const app = new Vue({
  el: '#app',
  data: {
    types: {}
  },
  methods: {
    pushValue(key, value) {
      if (this.types.hasOwnProperty(key)) {
        if (this.types[key].hasOwnProperty(value)) {
          const orgValue = this.types[key][value];
          orgValue.push([]);
          this.$set(this.types[key], value, orgValue);
        } else {
          this.$set(this.types[key], value, [[]]);
        }
      } else {
        this.$set(this.types, key, {
          [value]: [ [] ]
        });
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  <div>
    <p>pushValue(key, value)</p>
    <button v-on:click="pushValue(1, 'a')">(1, 'a')</button>
    <button v-on:click="pushValue(1, 'b')">(1, 'b')</button>
    <button v-on:click="pushValue(1, 'c')">(1, 'c')</button>
    <button v-on:click="pushValue(2, 'a')">(2, 'a')</button>
    <button v-on:click="pushValue(2, 'b')">(2, 'b')</button>
    <button v-on:click="pushValue(2, 'c')">(2, 'c')</button>
  </div>
  <div>{{ types }}</div>  
</div>

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

The asynchronous AJAX request is finished after the function call has been made. This can be achieved without using

I am in search of a solution that will allow an AJAX API call to finish before the containing function does without relying on jQuery as a dependency for just one REST call... After going through multiple solutions, all of which involve using jQuery, I ca ...

What is the preferred approach in JavaScript: having a single large file or multiple smaller files?

Having a multitude of JavaScript files loaded on a single page can result in decreased performance. My inquiry is this: Is it preferable to have individual files or combine them into one JavaScript file? If consolidating all scripts into one file is the ...

Send the Vue component as an argument to the function

Currently, I am in the process of transferring a project to Vue and utilizing Muuri as a layout manager. In my code, I have the following snippet: grid.add(itemElem, { layout: false, active: false }); The variable itemElem used to be an HTML element c ...

Ways to terminate and fulfill a promise

Each time I execute this snippet of code, a promise is returned instead of the data being inserted into my database. Unfortunately, I am unable to utilize the await keyword due to it not being in a top-level function. Specifically, I receive the message: & ...

Include backing for the trial syntax 'classProperties' within an npm module

I am facing a challenge while trying to publish an npm package containing some functions for my create-react-app project. The functions work fine when I import them from the js file within the create-react-app project, but I encounter an error once I insta ...

Loop through a nested array and output the playerId, playerName, and playerCategory for each player

update 3: After thorough debugging, I finally found the solution and it has been provided below. let values = { "sportsEntitties": [{ "sportsEntityId": 30085585, "sportsEntityName": "490349903434903490", "sportsEntityStartDate": "7878 ...

Leverage the power of jQuery datetime picker in an ASP.NET content page with a repeater control

Can anyone help me with adding a javascript tag to a content page of my asp.net application? The script is working fine with html tags, but it's not functioning properly within the content. Here is the code snippet that displays a datetime picker: &l ...

"Unexpected outcome: Angular's HTTP request for a JSON file yields an undefined

Learning Angular has been a challenging experience for me. I am currently working on reading a json file into a chart on my main app page to visualize temperature data from my PI. Despite trying various methods found online, I have not been successful so f ...

Angular UI Bootstrap Typeahead - Apply a class when the element is added to the document body

In my current project, I am utilizing angular bootstrap typeahead with multiple instances. Some of these instances are directly appended to the body using the "typeahead-append-to-body" option. Now, I have a specific instance where I need to customize the ...

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

What does ngModel look like without the use of square brackets and parenthesis?

Can you explain the usage of ngModel without brackets and parentheses in Angular? <input name="name" ngModel> I am familiar with [ngModel] for one-way binding and [(ngModel)] for two-way binding, but I am unsure what it means when ngModel ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

Passing a variable from a service to a controller in AngularJS

I recently developed a basic app that includes user authentication based on the guidelines found in this useful resource. The core components of my app are a userAccountService, which manages communication with the server, and a login controller that over ...

Need Root Directories in Browserify and Using NPM (eliminating the constant use of '../../../..' in both cases)

Despite my extensive search for a solution to this issue, I have been unsuccessful so far – even after referring to the amazing gist on improving local require paths and thoroughly reading the Browserify handbook section on Avoiding ../../../../... I am ...

What is the best way to display the HTML content being received from the database in the DOM?

I have received an object in this format [ { "BET": 57630343, "CUSTOMER": 181645, "SPORT": "MLB", "XX_FILL OPEN": "<button class=\"btn\" onclick=\"fillOpen(57630343)\">Fill Open</button>", "XX_VIEW": n ...

Creating a JSONArray in C# and transmitting the data to an Android application can be achieved using a few simple

Within my Android application, I am utilizing an MS SQL server database. For database access, I have created a c# script that is being called from the app similar to how PHP would be used. Specifically, in my login activity, users input their Username an ...

How can a Vuejs front-end web application coexist on the same host/domain as my server?

I'm struggling to understand the distinctions between a Vue.js front-end web app and my Node server. Once my app is completed, can I upload my server to the same domain where my web app resides? Can an API communicate with my server located at miwebsi ...

Interactive Notification System with MySQL, AJAX, and PHP

Seeking assistance for code conversion from async ajax to sync ajax. The current code is causing system lag after 20 minutes of inactivity. Likely issue resides within the code snippet provided below. function addmsg20(type, msg, data) { $('# ...

What is the correct way to insert a new key-value pair into an object within the state of functional components?

Is there a way to dynamically add key-value pairs to the initial state of an empty object in functional components, similar to computed property names in class components? I currently have an initial state of {}. const [choice, setChoice] = useState({}) ...

Using JavaScript to toggle the iron-collapse property

I've implemented multiple <iron-collapse> elements with unique IDs, each one corresponding to a <paper-icon-button>. On screens wider than 650px, I can interact with the <iron-collapse>s using their respective buttons. But on narrow ...