Ways to retrieve a specific value in an array of objects

When working with the p5 javascript library, there is a convenient built-in function called {key} that captures the key you press. For instance, using text(${key},200,200) will display the key pressed at position 200, 200 on the canvas. If I were to store this key value in an array and then retrieve it using console.log(), the output would be: Object {key: "a"}. So if you input "A", the letter A would be stored in the array. However, when trying to display this text using

text(Array_Of_Text[0],Xposition,Yposition);
you might just see "Object, Object" on the screen. This indicates that I need to somehow extract the actual value from the object, but I am unsure of how to accomplish this.

let Text = [];

function setup() {
  createCanvas(400, 400);
}

function draw() {
background(220);
text(Text[0],200,200);
console.log(Text[0])

}
function keyPressed()
{
  Text.push({key})
}

Answer №1

Avoid using curly brackets around key, instead simply use Text.push(key).

The correct built-in function is just key, not {key}. Adding the brackets turns it into an object following ES6 syntax. For instance, if key === "a", stating {key} is equivalent to stating {key: "a"}:

let key = "a";
console.log({ key });
console.log({ key: "a" });

The result will be "Object {key: "a"}" displayed twice. Comparing this using == or === won't work due to how JavaScript operates.

The same concept applies to any variable or data type: if valu === 200, then {valu} is essentially {valu: 200}:

let valu = 200;
console.log({ valu });
console.log({ valu: 200 });
//displays "Object {valu: 200}" twice

Answer №2

In JavaScript, it is possible to nest things and reference objects using notation like Text[0][0]. For example, you can declare a string variable as follows: let string = "hello"; console.log(string[0])
> "h"

if(Text[0].key !== undefined){
    console.log(Text[0].key)
}

(I believe this question has already been answered)

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

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

Error: AJAX encountered an unexpected token

An error message has appeared stating: Uncaught SyntaxError: Unexpected token : This error relates to the following line of code: data: userCoupon: $('#couponCode').val(), Here is the script in question: $(function() { $("#signInButton2"). ...

Having trouble assigning more than one custom named property in TypeScript for MUI v5 Palette

I am currently setting up multiple custom attributes to make future updates easier. Nonetheless, I'm encountering a challenge with implementing more than one custom property in MUI v5. TypeScript Error TS2717: Subsequent property declarations must hav ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

The functionality of save() is not compatible with mongoose.Schema

const Information = require('./Models/Information'); ... let sampleData = new Information( dataSample ); sampleData.save( function ( error ){ console.log('testing); if ( error ) { console.log('Error occurred while saving Informa ...

What is the best method for passing a JavaScript object to PHP using Ajax?

I have looked into similar questions like this and this, but none of them have helped me solve my issue. When I check the console log for my data, it displays the following: Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008" ...

How can you create a dynamic bounce effect for text with jquery animate()?

I've been experimenting with Jquery to achieve a bounce effect, here's what I have so far: Html: <div id ="animation">bounce</div> Jquery: $("#animation").animate({ marginTop: "80px" }, 1500 ) .animate({ marginBotto ...

Conceal the title attribute when hovering over a link using javascript/jquery

I have implemented the title attribute for all my links, but I want it to be hidden during mouse hover while still accessible to screen readers. var linkElements = document.getElementsByTagName('a'); for (var index = 0; index < linkElements. ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

Obtain input from request payload in WCF/ADO.NET Data Service

Why are my parameters getting lost when I try to post to an ADO.NET Data Service? This is what my code looks like: [WebInvoke(Method="POST")] public int MyMethod(int foo, string bar) {...} Here's how I'm making the ajax call using prototype.js ...

Putting off the jQuery UI autocomplete focus event

Currently, I am utilizing an autocomplete feature from version 1.8.23 of the jQuery UI library. Here is a snippet of my code: $(this).autocomplete({ autoFocus: true, minLength: 2, delay: 100, source: function(request, response) ...

I am looking to fetch information from a different Firestore collection by looping through data using a forEach method within an onSnapshot function

I'm struggling to grasp the concept of rendering data from Firestore in my project. I've searched extensively but haven't been able to find a solution that fits my requirements. Background Information In my Firestore database, I have collec ...

React JS Material UI disabled button under control

I am looking for some guidance. I am working on a feature where I need to disable a button conditionally. The idea is that if something is selected from my table, then the button should be available; otherwise, it should be disabled. MUI requires a boolean ...

Discover the method for retrieving the upcoming song's duration with jplayer

Hey there, I have a question regarding the jPlayer music player. Currently, I am able to retrieve the duration of the current song using the following code snippet: $("#jquery_jplayer_1").data("jPlayer").status.duration; However, I now want to obtain t ...

Exploring an Array in Javascript derived from a PHP Array

I have a PHP variable named $TillArray that contains an array. I am trying to pass this array to a Javascript function in order to display an Alert message for each item within the array. Below is the code I have been using: <script type="text/javasc ...

Modifying the theme of the Angular UI-Bootstrap datepicker

I am currently facing an issue with my angular datepicker, which is appearing oversized and covering almost 30% of the screen. Additionally, there are large gaps between the dates in the calendar view. After some investigation, I believe this problem may ...

Could not locate the express.js file

Currently in the process of learning express/node.js, but struggling to locate the page at localhost:3000/info You can view screenshots of my code below ...