Working with Javascript objects and arrays

Need assistance with manipulating/updating a JavaScript array. Hoping for some help.

The initial array looks like this:

 array('saved_designs'=array());

In Javascript JSON format:

 {"saved_design":{}}

I plan on adding a label and its associated array data:

 array("saved_designs"=array('label'=array('class'='somecssclass',styles=array(ill add more assoc elements here),'hover'=array(ill add more assoc elements here))))

Javascript version:

 {"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}

The goal is to be able to append/modify this array. If 'label' already exists, then update the corresponding sub-data. If 'label' doesn't exist, append a new dataset to the 'saved_designs' element.

If 'label' is not defined, add the following to the 'saved_designs' element:

 array('label2' = array('class'=>'someclass2',styles=array(),'hover=>array()')

I'm having trouble understanding the usage of [] and {} in JavaScript notation.

I may need further discussion as answers are provided. Here's the code I currently have:

 //saveLabel = label user chose for this "design"
 if(isUnique == 0){//update
      //prompt user if they want to overwrite design styles for specified html element
      if (confirm("There is already a design with that label ("+saveLabel+"). Overwrite this design's data for the given element/styles?")) {
           currentDesigns["saved_designs"][saveLabel]["class"] = saveClass;
           //edit other subdata here...
      }
 }else{//create new
      var newDesign = [];
      newDesign[saveLabel] = [];
      newDesign[saveLabel]["class"] = saveClass;
      newDesign[saveLabel]["style"] = [];
      newDesign[saveLabel]["hover"] = [];

      currentDesigns["saved_designs"].push(newDesign);//gives error..push is not defined
 }      
 jQuery("#'.$elementId.'").val(JSON.stringify(currentDesigns));

Thank you in advance. Hope everything is clear. Will update based on questions and comments. Shaun

Answer №1

It can get a bit tricky. JavaScript objects resemble a map or a dictionary from other programming languages. You can loop through them and retrieve their properties using object['property_name'].

Therefore, the distinction between a property and a string index is blurred. This appears similar to php code you are writing. In php, it's called an array, but since you are referencing values by a string, it will be serialized into an object in javascript.

var thing = {"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}

thing.saved_designs.label is equivalent to thing["saved_designs"]["label"].

In javascript, an array is a sequence that can only be accessed by integer indices. Arrays don't have explicit keys and can be created as follows:

var stuff = ['label', 24, anObject]

So, the error you're encountering about 'push not defined' is because you're not operating on an array as per javascript standards.

currentDesigns["saved_designs"] == currentDesigns.saved_designs

When you have an object and want to add a new key/value pair (i.e., property), you simply define the key and the value:

**currentDesigns.saved_designs['key'] = newDesign;**

If each design has a different label (which seems to be the case), the key would be that label (a string).


Furthermore, while you were defining the new design, this is how javascript understands it:

 var newDesign = [];

newDesign is an array. It contains various elements accessible by integer indices.

 newDesign[saveLabel] = [];

Since newDesign is an array, saveLabel should be a numerical index. The value at that index is another array.

 newDesign[saveLabel]["class"] = saveClass;
  newDesign[saveLabel]["style"] = [];
  newDesign[saveLabel]["hover"] = [];

Here, you are explicitly trying to use an array as objects. Arrays do not support ['string_key'].

This may seem to 'work', but only because in javascript arrays are objects and there is no strict rule against adding properties to objects freely. However, all these [] are not really aiding you.

var newDesign = {label: "the label", class: saveClass};

is likely what you are aiming for.

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

Putting a Pause on CSS Transition using jQuery

I am attempting to delay a CSS transition for an element by using a delay function, with an additional 0.2s applied to make it slide 0.2s later than the initial delay of the main wrapper. I am applying a class to give it a transition effect to slide from r ...

When using nativescript-vue to navigate to a Vue page, the props are cached for later

A couple of days back, I managed to resolve the issue I was facing with navigating through Vue pages. However, after fixing that problem, I made an error by mistakenly attempting to pass an incorrect key value to the Vue page I was redirecting to. When th ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Tips for executing an npm command within a C# class library

I am currently developing a project in a class library. The main objective of this project is to execute a JavaScript project using an npm command through a method call in C#. The npm command to run the JavaScript project is: npm start The JavaScript ...

Can select2 and a jQuery Virtual Keyboard work together seamlessly?

Is there a method to implement a jQuery virtual keyboard for inputting into a Select2 select box? The issue is that the dropdown in the Select2 component closes automatically when clicked away from, preventing the use of a web-based virtual keyboard. If ...

Issue with styling Icon Menu in material-ui

I'm having trouble styling the Icon Menu, even when I try using listStyle or menuStyle. I simply need to adjust the position like this: https://i.sstatic.net/n9l99.png It currently looks like this: https://i.sstatic.net/WeO1J.png Update: Here&apo ...

Learn how to easily incorporate a drop-down list into the material-UI Search component within the navbar to enhance the search results

I integrated a Material UI search bar into my React app's navbar following the instructions from the official documentation on MUI. However, the article does not provide any guidance on how to add a dropdown list when selecting the search input field. ...

Tips for implementing jQuery on HTML loaded post document.ready():

I've encountered a scenario where I have multiple HTML elements being rendered by a JavaScript function on the page: <a href="#" class="test1">Test</a> <a href="#" class="test2">Test</a> <a href="#" class="test3">Test< ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

Making an Ajax request from within an iframe using the easyXDM framework

I am currently utilizing easyXDM for enhancing the communication between a website and a shopping cart embedded within an iframe on my domain. Whenever a user adds an item to the shopping cart, I utilize easyXDM.Rpc to transmit the item details to the ifra ...

Comparison of jQuery, AngularJS, and Node.js

I'm a beginner in web development and I have some basic knowledge: HTML - structure of websites CSS - design aspect JavaScript - for adding interactivity Now, what exactly is jQuery, AngularJS, and Node.js? Upon researching, I discovered that jQue ...

The ImportJSON function in Google Sheets is failing to return results when using a path with an

I am utilizing ImportJSON (https://github.com/bradjasper/ImportJSON) for the purpose of creating a spreadsheet and importing JSON data. /* * The provided JSON feed is flattened to create a two-dimensional array while importing it into a Google Spre ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Error: The function expressJwt is not recognized as a valid middleware

As I delve into learning about middlewares, I encountered an issue when trying to import express-jwt. The syntax I used was: const expressJwt = require('express-jwt') To address the problem, I uninstalled the current version of express-jwt and i ...

Implementing swipe functionality to Bootstrap carousel

This is the code snippet I am working with: <div class="container"> <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="3000"> <!--Indicators--> <ol class="carousel-indicators"> ...

Transforming an array into a JSON object

I currently have an array structured like this: [ 'quality', 'print-quality: 4', 'x-dimension', 'Value: 21590', 'Value: y-dimension', 'Value: 27940', 'Value: ', 'Valu ...

Angular directive preventing default action but Chrome still loading image on drag

Has anyone encountered an issue with an angular directive that is not successfully preventing Chrome's default action? Below is the code for the directive in question: app.directive('fileDrag', function () { return { restrict: ' ...

Utilizing HTML5 canvas to extract pixel data from an image loaded from an external source

When it comes to security reasons, doing it directly may not be feasible. Nevertheless, there are rumors circulating about certain image-hosting platforms that permit the use of their images in a comparable way (could Google Picasa be one?). I might be mis ...

AngularJS ng-show will not function properly with newly added DOM elements

I am encountering an issue with ng-show directives on dynamically added DOM elements in AngularJS. The directives work fine when the page initially loads, but new elements that are added later do not have their expressions evaluated. Is there a way to prom ...

Guide on transmitting information from two separate pages to a PHP script simultaneously using an AJAX request

Looking to gather user information from a form and pass it onto another page smoothly. Origin Site <form action="destination.php" method="post"> Name: <input type="text" name="name"> Email: <input type="text" name="email"> <input typ ...