Retrieve the title of an item stored within a list

Let's say I have an array filled with objects - exactly 10 of them, each with unique names.

var upgrades = [
tree = {price: 20, rate:0.5, owned:0},
irr = {price: 80, rate:1, owned:0},
press = {price: 150, rate:2, owned:0},
cracker = {price: 400, rate:7, owned:0},
gmo = {price: 1000, rate:10, owned:0},
shack = {price: 1500, rate:13, owned:0},
truck = {price: 2000, rate:14, owned:0},
factory = {price: 5000, rate:18, owned:0},
rr = {price: 9000, rate:25, owned:0},
mGadget = {price: 15000, rate:30, owned:0},
];

I would like to extract the name associated with each object and store it in a string variable.

var x=upgrades[0].getObjName

In theory, x should now be equivalent to 'tree'; Is there a way to achieve this without having to introduce a 'name' variable within my objects?

Answer №1

To ensure your code functions correctly, make sure you are creating keys for the objects in the array rather than global variables. Start by correcting the syntax to create an array of objects structured like this:

var upgrades = [
  { tree: {price: 20, rate:0.5, owned:0} },
  { irr: {price: 80, rate:1, owned:0} },
  { press: {price: 150, rate:2, owned:0} },
  { cracker: {price: 400, rate:7, owned:0} },
  { gmo: {price: 1000, rate:10, owned:0} },
  { shack: {price: 1500, rate:13, owned:0} },
  { truck: {price: 2000, rate:14, owned:0} },
  { factory: {price: 5000, rate:18, owned:0} },
  { rr: {price: 9000, rate:25, owned:0} },
  { mGadget: {price: 15000, rate:30, owned:0} },
];

Once this is done, utilize Object.keys() to retrieve the first key from each object within the array:

var x = Object.keys(upgrades[0])[0];
console.log(x); // --> tree

Answer №2

Your array seems to be incorrect. There should not be identifiers for array elements. It should look like this:

var upgrades = [
 {price: 20, rate:0.5, owned:0},
 {price: 80, rate:1, owned:0},
 {price: 150, rate:2, owned:0},
 {price: 400, rate:7, owned:0}
];

Therefore, you cannot retrieve an element of the array by name; you must do so by index.

var x = upgrades[0]

If you wish to use named identifiers to access elements, then you should consider using objects instead of arrays.

var upgrades = {
    tree : {price: 20, rate:0.5, owned:0},
    irr : {price: 80, rate:1, owned:0},
    press : {price: 150, rate:2, owned:0},
    cracker : {price: 400, rate:7, owned:0}
}

 var x = upgrades.tree
 

To check by identifier in array:

Follow this example to retrieve array elements by identifier. Simply add a property to your objects in the upgrades array called 'identifier', and search for the specific identifier.

var upgrades = [
   {identifier : 'tree',price: 20, rate:0.5, owned:0},
   {identifier: 'tiger',price: 80, rate:1, owned:0}
];

var obj = upgrades.filter(function(elem,index){
   return elem.identifier == 'tree'
})
console.log(obj)

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

Sending information to a child component causes the parent's data to be modified as well

Transferring information from the parent to the child component has always been easy for me. However, I recently encountered an issue where updating the data in the child component also updates the data in the parent component simultaneously. Now, I am loo ...

Guide to creating flexible routes with multiple changing parameters in Vue 3 using Vue Router

What is the best way to implement dynamic routes with multiple dynamic parameters in any order using Vue 3 and Vue Router? These parameters should be able to be passed in any order. In our web application, we have over 500 views which makes it impractic ...

Dealing with an XML file using JavaScript

Is it possible for JavaScript to interact with an XML file fetched using AJAX? I have a server-side XML file and want to fill fields based on its content. Can I simply read "xmlfile.xml" directly from the server, extract values in JavaScript from the res ...

Arranging an array as values are inputted

My goal is to have the array automatically sort itself as the user enters values. Here's what I have done so far: void MoveRight(int *a,int n, int startIndex) { int j,temp; j=n-1; for(int i=startIndex;i<n;i++) { temp = ...

Using three.js to retrieve the camera's position using orbit controls

In my journey using three.js orbit controls, I have encountered a challenge of making a skybox follow the camera's position. Despite scouring the internet, I have not come across a suitable solution. My query is straightforward - how can I obtain the ...

PowerShell 5 returns a string instead of a JSON object for REST requests

Currently, I'm sending a GET request to a REST endpoint and receiving an object as a response. However, the Content subcategory and data within that are both of type String. How can I ensure that the entire response is formatted as an object so that I ...

Showing Sequelize validation errors in Express API: a comprehensive guide

In my Node.js/Express API with Sequelize ORM running MySQL, I have an Organization model that enforces a 2-100 character rule under validation. When this rule is violated in the first code snippet below, the err item from the catch block in the second code ...

What are the steps for retrieving a JSON object within an array?

var jsonData = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue" :{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text" :"Size32","price":"22","isSelec ...

Populating arrays with values depending on other criteria

I am currently developing a program that involves rolling dice. Based on the results, players can select certain scores (such as x3, x4, etc.) and I need to find a way to track how many times each value appears when five dice are rolled. Essentially, I nee ...

How can I fill in 3 textboxes with the selected Autocomplete value in MVC 4?

I am trying to implement autocomplete functionality in my form, where a text box is already attached to autocomplete. However, I am unsure how to trigger the ActionResult (which returns JSON) when a value is selected, extract the JSON result, and populate ...

Issue Installing Npm Package (detected 23 security vulnerabilities)

My attempt to install the package resulted in an error message. How can I resolve this issue? ...

What is the best way to implement a scroll to top/bottom button globally in Vue?

I have created a scroll-to-top and scroll-to-bottom button for my application. However, I want to make these buttons accessible globally throughout the app without having to repeat the code in every page where the component is needed. Currently, I am inclu ...

What is the process for modifying the headers of a post request in Express when

I have a Node/Express application and I'm looking to incorporate an image upload feature into an order form. While I can successfully use the action link in the HTML form to perform a POST request, I also want my JavaScript file associated with this ...

Ways to select a random row from a MySQL database

<button onclick="myUniqueFunction()">Press here!</button> <?php function myUniqueFunction() { $con = mysqli_connect("mysql.hostinger.no", "u452849516_altge", "password", "u452849516_altge"); $query = "S ...

Encountering a problem with NodeJS and ExpressJS Router.use()

Encountering an Error: // Necessary module imports // Setting up view engine app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.ur ...

Discovering hidden Mixed Content problems on a secured website can be a challenging task

After deploying a simple PWA application on the NGINX server, which was created using Vue CLI, I decided to use hash mode instead of history mode for the Vue router. Even though the website is secure: https://i.sstatic.net/CLfUr.png I am encountering th ...

Retrieve data from the MySQL database based on the search input field and dynamically update the options in the

I'm facing a programming challenge that I perceive to be at an advanced level for me. Currently, I have a custom search field in my registration form. However, I am looking to transform it into a dropdown menu that pulls user values from MySQL databas ...

Oops! Before proceeding, make sure to call TestBed.initTestEnvironment() first

Currently, I am experimenting with testing a service in Angular. Below is the code snippet I am working on: describe('AddressService', () => { let service: AddressService; let injector: TestBed; let httpTestingController: HttpTesting ...

When a npm package consists of multiple files, what is the best way to import them?

I have an npm package that consists of three files in the dist folder, generated by webpack: https://i.sstatic.net/td5Us.png Within the package.json file, I have designated the sample.js file as the main one: "main": "dist/sample.js", ...

"Is it possible to disable the transition animation in mat-sidenav of Angular Material without affecting the animations of

My Angular application features a mat-sidenav that is organized like this: <mat-sidenav-container> <mat-sidenav [mode]="'side'"> <!-- Sidenav content --> </mat-sidenav> <mat-sidenav-content ...