Accessing specific elements within multi-dimensional arrays using JavaScript

I've embarked on the exciting journey of creating my own 'Choose Your Adventure!' game, but I've hit a snag. I'm struggling to effectively target specific values within the multi-dimensional array I constructed. In order to add some depth to my game, I introduced a unique 'dealer/trader' character who offers various items for sale.

var dealer = [
  [
    {type: "weapon", cost: 250, name: "Claymore"},
    {type: "weapon", cost: 75, name: "Dagger"},
    {type: "weapon", cost: 350, name: "Magic Staff"},
    {type: "weapon", cost: 150, name: "Sword"},
    {type: "weapon", cost: 125, name: "Bow"},
    {type: "weapon", cost: 125, name: "Crossbow"},
    {type: "weapon", cost: 5, name: "Arrow"},
    {type: "weapon", cost: 15, name: "Bolt"}
  ],
  [
    {type: "clothing", slot: "head", name: "Helmet"},
    {type: "clothing", slot: "head", name: "Hood"},
    {type: "clothing", slot: "chest", name: "Chestplate"},
    {type: "clothing", slot: "chest", name: "Tunic"},
    {type: "clothing", slot: "chest", name: "Robe"},
    {type: "clothing", slot: "leggings", name: "Legplates"},
    {type: "clothing", slot: "leggings", name: "Leggings"},
    {type: "clothing", slot: "leggings", slot: "Undergarments"},
    {type: "clothing", slot: "feet", name: "Boots"},
    {type: "clothing", slot: "feet", name: "Armored Boots"}
  ]
]

I've also written a function that manages transactions with the dealer, like purchasing items, but I'm unsure how to pinpoint specific values/arrays. Below is my attempt to code a solution.

function merchant() = {
    var armor = function(slot, name, material)  {
        if(dealer[2].slot === "feet" && dealer[2].name = "Boots"}
            money -= 10;
        }
    }
}

My intention is to access the second array containing clothing items and search for items with the slot 'feet' and name 'Boots'. Hopefully, this approach will yield the desired results!

Answer №1

My suggestion is to use an array of merchant objects in the merchants array. This will allow for more detailed information about each merchant, including their items. I have implemented two find methods, one with static arguments and another with key-value parameters.

Note: I included a cost field for boots in your example as it seemed relevant.

var merchants = [{
  name : 'Weapons Merchant',
  items : [
    {type: "weapon", cost: 250, name: "Claymore"},
    // more weapon items...
  ]
}, {
  name : 'Armor Merchant',
  items : [
    {type: "clothing", slot: "head",     name: "Helmet"},
    // more clothing items...
    {type: "clothing", slot: "feet",     name: "Boots",       cost : 10},
    {type: "clothing", slot: "feet",     name: "Armored Boots"}
  ]
}];

// rest of the code...
<div id="out"></div>

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

Neither req.body nor req.file contain any data

Hey everyone, I'm new to coding and currently working on creating a basic markdown blog. However, I'm facing an issue where req.body doesn't contain my markdown field and req.file is undefined when trying to upload an article. I'm unsur ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

Question about using React, NPM, Vite, Babel, and Node.js together

I want to confirm my understanding. So, if I decide to create a react 'app' and incorporate babel for jsx support. Then, I opt for vite for enhanced development runtime and packaging. Lastly, I utilize node.js to execute my code. To sum it up, ...

The Nextjs Image was preloaded using link preload, but it remained unused after a short period following the window's load event

I've encountered an issue while working with Next.js, a React-based framework. I am attempting to display the logo.png image using the Image component provided by Next.js. My image is stored in this folder: public/img Here is the code I'm using ...

Concealing a div based on a condition

Having difficulty concealing a div once a specific condition is met. The condition depends on the user logging into a web application. In my CSS file, I have set the multipleBox div to visibility: hidden, along with other styling attributes like border co ...

Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original. Check out my code below: window.onload = function() { ImageObjSketch = new Image(); // URL ImageObjSketch.src = 'https://i.imgur.com/75lATF9 ...

Set a timer to run only during particular hours of the day, and pause until the next designated time

I need assistance with integrating a function called "tweeter" into my code so that it runs at specific times throughout the day - 09:00, 13:00, 17:00, and 21:00. Currently, the function runs continuously after the initial hour check is completed, instead ...

Creating a group object based on ID using react-native and JavaScript - a step-by-step guide

I have an array of objects that I need to reorganize so that each object with the same guid is grouped together. For instance, given this array; [ {"guid":"3a03a0a3-ddad-4607-9464-9d139d9989bf","comment":"text&quo ...

Generating numerous div elements with jQuery's zIndex property

While attempting to create a function that runs on the $(document).ready() event and is supposed to generate a new div, I encountered an issue. Whenever I try to create another div with the same DOM and Class attributes but in a different position, a probl ...

To avoid the browser context menu from appearing when interacting with a d3.js element, simply employ a different way of clicking

Currently, I have a d3.js element plotted in the form of a rectangle: // draw rectangle svg.selectAll(".rect").append("rect") .attr("y", 10) .attr("x", 10) .attr("height", 5) .attr("width", 5) .on("contextmenu", function (d, i) { // ...

Flipping and rotating images using the power of HTML5 Canvas

Hello, I need assistance with my Electron app that arranges images for batch printing on an industrial printer. The issue I am facing is with images flipping or being mirrored unpredictably. Below is the code snippet responsible for determining whether an ...

The local server for handling HTTP requests has ceased to operate

Recently, I set up the NPM package along with the http server within the "server" directory. Initially, everything was functioning smoothly; however, the server abruptly ceased operating. Upon attempting to launch the local http server, an error message a ...

Implementing dynamic props in Vue2 component by passing arbitrary named variables

Having recently delved into Vue, I am facing a challenge that has left me scratching my head after consulting the documentation: I am struggling to pass an arbitrarily named variable as a prop to a component instance. As per my understanding, props serve ...

Navigating in AngularJS with various URL parameters

Within my application, I am in need of using routes that require multiple attributes from the URL to be passed into PHP. The current setup that is functioning correctly is as follows: .when('/jobs/:type', { templateUrl: function(attrs){ ...

python using selenium to bypass javascript popups

I have a project where I need to visit a specific website and interact with it using the Python selenium module. However, I am encountering a popup (a cookie acceptance form) when trying to access the site with a bot. I must accept this popup in order to p ...

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

What is the best way to enable an image to be moved on top of another image?

Is there a way to allow users to drag around an image that is positioned on top of another image in an HTML file? I want the superimposed image to stay within the boundaries of the underlying image. Any suggestions on how this can be achieved? <html& ...

The pause button will still function, even if the scrolling feature is enabled

I've successfully implemented a feature that pauses and plays the video on scroll when it reaches a certain pixel height. However, I'm facing an issue where the code automatically plays the video whenever the scroll position is more than 13500px ...

What is the best way to execute a JavaScript function when the onSelect event of a jQuery datepicker is

Is there anyone who can assist me? I am currently working with a JavaScript function: function updateAb(param){ some manipulation } I also have a datepicker jQuery plugin that I am using for the onSelect event, like so: $( ".datepicker").datepicker({onS ...

Node.js seems to be playing tricks on me. It's creating bizarre names and tweets by utilizing arrays

Trying to decipher a snippet of code that is tasked with generating random tweets has left me puzzled. Specifically, I find myself stumped when it comes to understanding the line: Math.floor(Math.random() * arr.length) I believe this line selects a rando ...