Getting Started with Arrays in JavaScript

I've been working on improving my JavaScript skills but I seem to have hit a roadblock.

var schemes = {
    "own" : {
        "creatures" : ["creature1","creature2","creature3","creature4"],
        "spells" : ["spell1","spell2","spell3","spell4"],
        "items" : ["item1","item2","item3","item4"]
    },
    "enemy" : {
        "creatures" : ["creature1","creature2","creature3","hidden"],
        "spells" : ["spell1","spell2","hidden","hidden"],
        "items" : ["item1","item2","item3","hidden"]
    }
};

Here is the array I'm working with.

I am attempting to use a for each loop, similar to what I know from PHP, but it seems that JavaScript is treating 'schemes' as an object and therefore I can't do:

for (var i=0;i<schemes.length;i++) {
 //code 
}

What could I be missing? The console says 'schemes.length' is undefined.

Answer №1

schemes is essentially considered an "object" and therefore does not have a .length property.

To retrieve an array of the keys, you can utilize Object.keys(schemes) or:

for (var key in schemes) {
    var el = schemes[key];
     ...
}

Answer №2

It's important to note that schemes is not an array but actually an object.

Let's illustrate this further:

myData = { 'x' : 10, 'y' : 20, 'z' : 30 } // example of an object

myNumbers = [ 10, 20, 30 ] // example of an array

Here are some operations you can perform with these variables:

for (var property in myData) {
    console.log(property + ": " + myData[property]);
}

for (var j = 0; j < myNumbers.length; j++) {
    console.log('Value at position ' + j + ':' + myNumbers[j]);
} 

Answer №3

Concepts is a concept. It may be beneficial to convert it into an array of concepts.

var concepts = [{
    "personal" : {
        "ideas" : ["idea1","idea2","idea3","idea4"],
        "thoughts" : ["thought1","thought2","thought3","thought4"],
        "visions" : ["vision1","vision2","vision3","vision4"]
    },
    "opposing" : {
        "ideas" : ["idea1","idea2","idea3","hidden"],
        "thoughts" : ["thought1","thought2","hidden","hidden"],
        "visions" : ["vision1","vision2","vision3","hidden"]
    }
}];

You can then explore the array like this:

for (var i=0;i<concepts.length;i++) {
  alert(concepts[i].ideas[1]); //alerts idea1 (2x)
}

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

Retrieving ng-repeat $index with filtering in AngularJS controller

I am facing a challenge with my ng-repeat list and filter in AngularJS. I am unable to retrieve the visible $index value from inside my controller. Although I can display the index easily and see it change dynamically when the list is filtered, I am strug ...

Filter out the selection choice that begins with 'aa' in the drop-down menu

Here is a select field with various options: <select id="sel"> <option value="1">aadkdo</option> <option value="2">sdsdf</option> <option value="3">aasdfsddkdo</option> <option value="4"> ...

Ajax script causes error 403 when loading content while scrolling

Currently in the process of creating a blog using the HubSpot platform. The primary goal is to have blog posts load dynamically as users scroll down the page. I came across a script that claims to achieve this functionality and is designed specifically for ...

Selectors within 'not' in document.querySelectorAll are failing to function as expected

I've been attempting to find a way to replace the jQuery .not() function with native JavaScript, but so far my attempts using document.querySelectorAll have not been successful. Here is what I am trying to achieve - converting this jQuery selector in ...

JQuery droppable no longer retains its initial class

When an element is dropped on it, I am able to obtain the id but not the class of that element... HTML <div id="drag" class="two">drag</div> <div id="drop" class="one">drop</div> JS $(document).ready(function(){ $("#drag").d ...

Is it possible to retrieve JavaScript object properties using HTML elements?

I have fetched an array of objects using jQuery.getJSON(). Each object should be represented by an HTML div element, allowing users to click on the element and access all properties of the corresponding object. What is the most efficient approach for achie ...

Tips for avoiding infinite re-render loop when updating state in React/Next.js

I currently have a unique Next.js application that showcases randomly selected YouTube videos. The state within the app is structured as follows (managed by Redux): const state = { entities: { videos: { 'vidId1': { ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

Extracting the id of an element using jQuery

The desired outcome is for the code to print the id of the selected div, but it's not working as expected. I've reviewed it multiple times but couldn't pinpoint the error. Any assistance would be greatly appreciated. Here is the HTML: < ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

javascript mysql and php clash when it comes to loading

I am encountering an issue where I cannot fetch data from my phpMyAdmin database using php code when loading the map api that utilizes javascript. Currently, only the map javascript is being loaded. I have valuable data stored in my database and any assis ...

Retrieving Information from an API with Custom Headers in React Native

I have an API that necessitates specific headers for access. Without these headers, a browser displays the following error: Code: 4101 Message: Header X-Candy-Platform is required However, when the headers are provided, the API returns a json response. ...

Tips for eliminating unnecessary module js calls in Angular 9

https://i.sstatic.net/3R7sr.png Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module J ...

Implementing a PHP back button to navigate through previous pages

Currently, I am in the process of coding a project. In this project, there are a total of 10 pages, each equipped with back and forward buttons. However, when I attempt to navigate using either javascript:history.go(-1) or $url = htmlspecialchars($_SERVER ...

Personalizing the dimensions of audio.js

I recently integrated the audio.js plugin into my website. I've added the necessary code to the header.php file located in the includes folder. <script src="audio/audiojs/audio.min.js"></script> While the player appears correctly on othe ...

Show picture in web browser without the file extension

Is there a way to display an image in the browser without the file extension, similar to how Google and Unsplash do it? For example: Or like this: ...

Requests exceeding 8 kilobytes

I am looking to measure the round trip time between a client and server. Users have the option to determine the size of the request/response message they want to send. On the client side, I am using the Ajax-Post method to transmit 100 messages every 100 m ...

The Node.contains() function in JavaScript does not verify the presence of inner child elements

I have developed a custom DatePicker component for my React app and I am facing an issue with hiding it on outside click, similar to how I handled other components like Select Dropdown. To address this problem, I created a custom hook: export default (ref, ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

Step by step guide on serializing two forms and an entire table

I have been attempting to serialize data from two forms and the entire table simultaneously. While the form data is successfully serialized, I am encountering difficulty in serializing the table records as well. Below is the code snippet of what I have att ...