Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down.

My dilemma arises when I select button 2 and then click the up button. I want button 2 to move up to position button 1. To achieve this, I need to utilize an attribute in J-SON. However, I am struggling with how to swap the entire J-SON data, specifically switching the positions of button 2 with button 1, and vice versa for the down arrow.

Although I searched for swapping techniques on Google, the results only show how to swap items in an array, whereas I require the complete J-SON object to be swapped.

up(){ 
  exchange(this.jsondata,up,up+1); 
} 

private exchange(array: any, x: any, y: any) { 
  const temp = array[x]; 
  array[x] = array[y]; 
  array[y] = temp; 
  return array; 
}

The goal is to rearrange the button positions upon clicking the up or down buttons.

Answer №1

When it comes to swapping two elements in an array, your exchange function appears to be correct.

However, you are only passing 2 parameters when your function actually requires 3 parameters:

  • the array where the items are stored
  • the first item to be swapped
  • the second item to be swapped

If your buttons were within an array named myButtons, you would likely need to call it like this:

up(myButtons, up, up+1);

Some additional points to consider:

  • Be cautious about the names you give your parameters. Using "Array" as a variable name is not recommended since it's a global JavaScript object.
  • The name "up" is used for both a function and a variable, which can lead to confusion.
  • Your function currently returns the array passed as a parameter, which may not be necessary since arrays are passed by reference. You could make your function immutable and return a new array, or simply modify the existing array without returning anything.

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

What is the best way to create a keyup event for the entire document except for one specific element?

Looking for some advice on how to handle a specific code scenario. Here's what I have: $(document).ready(function(){ $(document).on("keyup",function(e){myFunction(e)}); }); function myFunction(e){ console.log("hi"); } In ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Where can I locate the list of events supported by CKEditor 4?

Looking for the list of available events I attempted to locate the event list in the official documentation, but unfortunately came up short. I resorted to searching through the source code using .fire("/s+") to identify all available events. However, thi ...

The initial values of Typescript class members are merged directly into the class constructor

This issue has been well documented (check out Initializing variables inline during declaration vs in the constructor in Angular with TS on SO for reference), but it can lead to challenging memory problems. Take a look at the example below class Bar { ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

AngularJS substitution with regular expressions

Looking to replace specific words in HTML content within <div> and <p> tags upon page load. Utilizing angularJS to achieve this task. This is my current function: var elementsList = e.find('p'); var regex = ('[^<>\& ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Exploring Angular 7: Leveraging class inheritance and the powerful httpClient

It has come to my attention that my services are quite repetitive. In an attempt to enhance them, I decided to delve into super classes and inheritance in Angular. However, I have been struggling with the constructor and super calls. Despite TypeScript com ...

When refreshed using AJAX, all dataTable pages merge into a single unified page

I followed the instructions on this page: How to update an HTML table content without refreshing the page? After implementing it, I encountered an issue where the Client-Side dataTable gets destroyed upon refreshing. When I say destroyed, all the data ...

The type '{ children: Element; }' is lacking the specified properties within type - NextJS version 13.0.6 with TypeScript version 4.9.3

Currently, I am delving into NextJS / TypeScript and have come across a type error. The component structure is as follows: interface LayoutProps { children: React.ReactNode; title: string; keywords: string; description: string; } const Lay ...

Utilizing the Teams web app within my customized electron application

I've been developing an electron app and am trying to integrate the MS Teams web app into it. I've successfully displayed MS Word, MS Powerpoint, and other apps using window.loadURL(''), but I'm experiencing issues with MS Teams. D ...

Utilizing the Vue feature of dynamic route naming within a component's function

Currently, I am working on creating a dynamic view rendering using Vue and Laravel. However, I am facing difficulty in understanding how to pass the dynamic parameter to the component function. Router.map({ '/cms-admin/:page': { comp ...

Error Alert: missing property data in angular 5 type

I attempted to design an interface in interface.ts. The data consists of an array of objects inside the Column. Below is the code for my interface: export class User { result: boolean; messages: string; Column=[]; data=[]; } export class Column { name ...

Is it possible to process HTML and JavaScript as a request in JMeter?

After receiving a response, I noticed that the HTML body contains a hidden form along with an internal JavaScript function to submit the form (view snapshot here). Is there a method in JMeter to execute JavaScript code that directly submits a form? I am ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Tips for utilizing JavaScript to upload a file in Webform and make it accessible in the global PHP variable $_FILES

I'm feeling a little overwhelmed and frustrated. I've come across a bunch of solutions, but none of them seem to work fully or correctly!? My task is to create an HTML form that allows users to upload one or more files to the web server using AJ ...

Does adding a callback to object.ngOnDestroy() replace its internal onDestroy() method?

I'm enhancing the drag and drop feature in Angular <div cdkDropList appImprovedDropList> <div cdkDrag>item 1</div> <div cdkDrag>item 2</div> <div cdkDrag>item 3</div> </div> The directive appImpro ...

Preventing page reload when altering parameters in Angular 9

I have recently utilized Angular9 along with PathLocationStrategy {provide: LocationStrategy, useClass: PathLocationStrategy}, The issue I am facing is: Whenever I use form.submit() to send data to the backend, the backend then redirects back to the c ...

featherlight.js - Execute code when modal is triggered

Situation with HTML <div id="form-lightbox"> <div class="form"> <div id="ajaxreplace"> <script type="text/javascript"> jQuery(function() { jQuery.ajaxReplace({ //parame ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...