Vue method for swapping array content by key

I am encountering an issue with the way I add contents to an array using keys instead of indexes.

After experimenting in a sandbox environment, a few observations were made:

  • Despite adding contents to the array via key, they do not appear and the length remains 0 (even though they are present)
  • I am unable to swap the contents between various array items.

Is there a specific rule or limitation when using keys instead of indexes for viewing and swapping array contents?

For reference, I have created a basic fiddle at: https://jsfiddle.net/26Lve48g/

new Vue({
  el: "#app",
  data: {
    blah: [],
  },
  created() {
    this.blah['abc'] = 'foo';
    this.blah['def'] = 'bar';
  },
  computed: {
    // Displays the value correctly in the HTML window
    blahAbc() {
      return this.blah['abc'];
    },
    // Displays the value correctly in the HTML window
    blahDef() {
      return this.blah['def'];
    },
  },
  methods: {
   swap(a, b) {
     const tmpA = JSON.parse(JSON.stringify(this.blah[a]));
     const tmpB = JSON.parse(JSON.stringify(this.blah[b]));
     Vue.set(this.blah, this.blah[a], tmpB);
     Vue.set(this.blah, this.blah[b], tmpA);     
   }
  },
})

Answer №1

[] utilizes both numeric and string values as indexes,

However, elements added using string indexes are considered as properties of the array object rather than true array elements.

The length property and array methods only affect elements with numeric indexes.

To learn more about this, visit

{} uses strings and Symbols as keys.

Even though objects can be added to arrays,

In your situation

<div id="app">
 <button @click="swap('abc', 'def')">Swap</button>
 <p>Blah:{{ blah }} {{ blah.length }}</p>
 <p>BlahABC: {{ blahAbc }} </p>
 <p>BlahDEF: {{ blahDef }} </p>
</div>

Running the code above displays

Blah:[] 0

BlahABC: foo

BlahDEF: bar

It is clear that blah does not have a numeric index, hence the length returns 0.

Here is a live example on JSFiddle https://jsfiddle.net/szu7f4hn/
This demo swaps the contents of the array when the button is clicked.

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

Node.js Interceptor: A powerful tool for controlling and

I've been attempting to construct an interceptor in Node.js, but I haven't had much success. I'm trying to create the interceptor to capture each request and include a unique header retrieved from the Koa context. Basically, when making an ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

What is the significance of the NS_ERROR_UNKNOWN_PROTOCOL error code?

When attempting to make an AJAX request using Angular 1.5.9, my code is as follows: $http.get('localhost:8080/app/users').then(function(resp) { ... }); However, I am encountering an error that reads: "NS_ERROR_UNKNOWN_PROTOCOL" (...) stack: "c ...

Ways to darken a theme when displaying a pop-up

I recently added a pop-up feature to my portfolio website and utilized Bootstrap classes to enhance its functionality. In order to make the pop-up object more prominent, I wanted to darken the background when opening the pop-up. However, some elements in t ...

Divide and Insert a Gap in Phone Number

I need help formatting a telephone number so that there is a space between every third and seventh character. var phoneNum = "02076861111" var formattedNum = [phoneNum.slice(0, 3), phoneNum.slice(3,6), " ", phoneNum.slice(6)].join(''); console ...

How come the output of the multiplication is not visible in the template using JavaScript, but it is visible when inspecting the element in Chrome DevTools?

I have integrated some JavaScript into my Django project to handle system calculations. However, I find it odd that something as simple as the result of a multiplication is not reflected on the webpage template but only in the Chrome Dev Tools. Below are ...

Try utilizing the Array.map method with a two-dimensional array

My current challenge involves a 2-dimensional Array where I am attempting to implement a "randomBool" function on each of the elements within it. The "randomBool" function essentially generates a random boolean value: const randomBool = () => Boolean( ...

Morris bar adjusts size when printing

I'm facing an issue with printing my Morris bar chart results. Everything looks fine in HTML, but when I try to print it, the layout seems off. Here is what I have tried so far: <script> function myFunction() { window.print(); } </script ...

Is there a way to implement a setTimeout delay in my puppeteer browser?

I wrote a function named waitForTimeout to introduce a brief delay that can be awaited once the browser navigates to a new page. function waitForTimeout(timeout) { return new Promise((resolve) => { setTimeout(resolve, timeout) }) } const puppet = () =& ...

The ultimate method for ensuring top-notch security in JavaScript JSON Inline practices

Utilizing varnish+esi, I am able to retrieve external json content from a RESTFul API. This approach allows for efficient request management and data refreshing without burdening the webserver with each individual request. For example: <head> .... ...

An image in Vuejs flickers into view and then quickly vanishes

I'm currently working on a website project with my team, and for the cover, I decided to use vue-parallaxy. <div style="position: relative;"> <parallax :fixed="true"> <img :src="images.cover" height="720px"/> < ...

Sending a document using the ng-file-upload directive to a Sails.js server

I am working on uploading a file to a sails.js application server using the ng-file-upload directive provided at this link. Here is the client-side code I am using to upload a pre-selected image: $upload.upload({ url:'upload/item-image' ...

Can you explain to me the concept of "face indices" in Three.js and how it functions?

I am attempting to use Three.js to build a unique irregular polyhedron. In order to achieve this, I have decided to utilize the PolyhedronGeometry feature (refer to the documentation). However, I am encountering difficulty in understanding the concept of ...

The equivalent of javascript setTimeout in Winforms

Is there a way to implement a setTimeout function in a WinForms application for auto-complete functionality after each keystroke in a textbox? As a primarily a web developer, I'm unsure of how to achieve this in a WinForms environment. I want to be ab ...

Creating HTML dynamically in ASP.NET: What's the best approach?

Throughout the past year, I've dabbled in ASP.NET on and off. However, I am currently facing a new challenge while working on a simple website that mainly consists of HTML and Javascript. On one specific page, I need to retrieve an XML file from the s ...

Preventing drag and drop functionality within the knockout js sortable feature

How can I selectively disable drag and drop on certain squares within a 5x5 grid while using the sortable feature in knockout js? Any suggestions or solutions for this specific use case? ...

Encountered a problem when attempting to upload images to Cloudinary through the front-end and save the information in a MySQL database using Axios on Node JS

I am currently working on a web application using React. I have implemented a form where users can input text data and upload multiple image files. The goal is to store the submitted images on Cloudinary along with other text data in a MySQL database. Unf ...

Automatically convert numbers entered into an input field into thousands with auto division formatting using JQuery Mobile

Currently, I am working on developing a form using jQuery Mobile. However, I have encountered an issue where when I use an input field with the attribute type="number," the numbers entered are automatically formatted using the thousands convention. Here i ...

Having trouble getting an Android WebView to display a javascript graph?

I have a webpage with a graph that utilizes javascript, jquery, bootstrap, and angular.js. I am attempting to load this graph in my android app using a WebView within the android.support.v4.app.Fragment. WebView webView = (WebView) rootView.findViewById(R ...

I'm encountering an issue with ESlint in my Vue.js project that I just can't seem to resolve

A couple of months back, I encountered this issue within my vue.js project. The error seems to be originating from lines 22, 23, and 24, which correspond to lines 45, 46, and 47 in the code block below. { "resource": "/C:/Users/Demo User ...