Using Javascript to generate a fresh object based on another object and then extracting it from an array

I have this sample constructor that creates new Loot objects:

function Loot(type, sellValue) {
    this.type = type;
    this.sellValue = sellValue; 
}

I want to extend these properties to other objects and add them to an array like so:

var inventory = [];

var stone = new Loot("craft", 20);
inventory.push(stone);

var hat = new Loot("clothing", 80);
inventory.push(hat);

var coal = new Loot("ore", 5);
inventory.push(coal);

var diamond = new Loot("ore", 400);
inventory.push(diamond);


console.log(inventory);

But the problem is that when I check my inventory, it shows (Loot, Loot, Loot, Loot) instead of the actual names of the items (stone, hat, coal, diamond).

How can I fix this issue? Do I need to implement some kind of inheritance?

Thanks!

Answer №1

The object does not recognize variable names like "stone." Instead, these names serve as references to the object itself without directly representing the data within the object.

Therefore, "stone" is just a label assigned to the same Loot instance that was initialized.

In this scenario, only one Loot object exists in your code.

If you examine the array using a debugger, it will indicate the type of object (Loot). To view the specific values stored within the object, you will need to expand the object and explore its contents.

Answer №2

However, when I attempt to view my inventory, it displays as (Loot, Loot, Loot, Loot) instead of showing the actual names of the items, (stone, hat, coal, diamond).

To see the names of the items in your inventory array, you will need to iterate through the array and log the .type properties of each item:

for (var i=0; i<inventory.length; i++)
    console.log(inventory[i].type);

Alternatively, you can create a new array containing only the item types using the map method:

var types = inventory.map(function(item) { return item.type; });
console.log(types);

Answer №3

It's important to note that the array cannot contain string keys. In this case, using an object is recommended for storing these items.

function Loot(type, sellValue){
  this.type = type;
  this.sellValue = sellValue; 
}

var inventory = {};
var inventory2 = {};

var stone = new Loot("craft", 20);
var stone1 = new Loot("craft1", 30);
var stone2 = new Loot("craft2", 40);

// Alternatively: 
inventory2['stone'] = stone;
inventory2['stone1'] = stone1;
inventory2['stone2'] = stone2;

console.log(inventory);   // Object {craft: Loot, craft1: Loot, craft2: Loot}
console.log(inventory2);  // Object {stone: Loot, stone1: Loot, stone2: Loot}

http://jsbin.com/aNiXolo/5/edit

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

determine the k stars that are in closest proximity to our planet

If we imagine a coordinate system for our Milky Way galaxy with Earth positioned at (0; 0; 0), and view stars as individual points, distances being measured in light years, there are roughly 10^12 stars making up the galaxy. The coordinates of these star ...

What are the steps to incorporating an Image in a React Native application?

My Image is not showing up when I try to render it using image uri, and I'm not sure why. Here is the code snippet I'm using in a React Native project. import React from 'react'; import styled from 'styled-components/native'; ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

Saving the previous component's DOM in a React application

Understanding the Root.js File const Root = () => ( <HashRouter> <div> <Route exact path="/" component={Main}/> <Route path="/main/:page" component={Main}/> <Route path="/detail ...

Switch out the icons within a return statement in JavaScript

Help! I have 5 empty star icons (<StarBorderIcon/>) displayed for a product on the material-ui website. I need to replace them with filled star icons (<StarIcon/>) based on the rating entered into a function. I attempted to use replace(), but i ...

Encountering issues with formData in nextjs 13 due to incorrect data type

In my NextJS application, I am using the dataForm method to retrieve the values from a form's fields: export async function getDataForm(formData) { const bodyQuery = { ....... skip: formData.get("gridSkip") ...

Freezing the OrderBy Directive in AngularJS ng-repeat While Editing

I am currently utilizing md-data-table and have implemented sorting options based on column. Below is my HTML code in pug format: table(md-table md-row-select multiple='' ng-model='vm.selected' md-progress='promise') //- col ...

Break down a string with various delimiters into an array with key-value pairs

Utilizing a module to facilitate the creation of booking orders on my website. This module offers a hook that triggers after a new booking is successfully created. The data I receive is stored in the variable booking_form, which contains the following in ...

JQuery hover effect for dynamically added elements

Currently, I am working on a webpage that will trigger an ajax call upon loading. The response data in JSON format will be processed and the elements will then be added to the DOM as shown below: $.ajax({ type: 'POST', url: "http://mysite.de ...

A guide to resolving a sinonJS stub issue

Trying to stub a request with SinonJS has been a challenge for me. I set up the mock request before each test to use fake data, but it's not working as expected. I attempted to use Promise.resolve for resolving, but that didn't work out either. ...

Ways to determine if a dynamically generated script tag has been successfully executed

Recently, I've been experimenting with dynamically creating a script tag: var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.charse ...

Understanding the readability of JavaScript arrays.ORDeciphering

Recently, I've been working with a JSON OBJECT that looks something like this { "kay1": "value1", "key2": "value2", "key3":{ "key31": "value31", "key32": "value32", "key33": "value33" } } However, I am interested in converting it ...

Is there a way for me to collaborate on a footer control with a different website?

Is it possible to seamlessly incorporate a footer from one website into another? Ideally, I want the footer HTML (and styles) to be dynamically inserted into different web pages. The common workaround is using an iframe, but this causes navigation issues ...

How can I retrieve XML information from a webpage?

I've been trying to incorporate some basic JSON data into my website, but despite experimenting with various ajax and JSON options, I haven't been able to achieve the desired results. What I'm looking for is a simple data request that appen ...

React JS - Breaking down the distinction between PublicTheme and PublicTheme

In my React project, I am currently working on creating the admin dashboard and designing the UI area for user interaction. I have encountered an issue where I am unable to separate the admin theme from the PublicTheme. Even when navigating to "/admin/lo ...

Is it possible to create a webpage where the header and footer remain static, while the content in the body can be dynamically changed

I am in the process of creating a webpage where main.html will load a page with a static header and footer that remains unchanged when navigation links are clicked. I'd like to achieve this using Javascript, with the body content being sourced from an ...

Ways to resolve the issue of a website displaying with extra whitespace at the bottom

Seeking assistance to resolve the issue with a blank space at the bottom of the web page. Refer to: http://www.khohanghoa.com I have dedicated the entire day to search for a solution and attempted to fix the problem. I have attempted to configure the CS ...

Strange behavior observed with Nuxt Js asyncData method returning values

Currently, I am engaged in a project using nuxt js/vue js. The project requires me to interact with multiple REST APIs. To accomplish this task, I am utilizing the asyncData() function provided by nuxt js to make the API calls within the page component. i ...

Error message 'Invalid Request' encountered when submitting a POST form

When I submit the form in index.html, it is supposed to redirect to results.html to display some information based on the submitted form. However, I am consistently receiving a Bad Request HTTP response and attempting other solutions found on Stack Overflo ...

Getting the inner element of a particular child from the parent div using selenium with javascript

<div class="A"> <svg> ... </svg> <button> <svg> ... </svg> </button> <svg> ... </svg> </div> <div class="A"> <svg> ... </svg> <button> ...