An assortment of elements with conditional statements

Can anyone help me with a function that returns the price of an item from a list?

What happens if the item is not in the list? If it isn't, I want to display

"No item found with that name"

Any suggestions on how to achieve this?

let items = [{
    itemName: "Effective Programming Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Creation 3005",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Finding Your Center",
    type: "book",
    price: 15.00
  }
]

function priceLookup(array, item) {
  let results = 0;
  for (let i = 0; i < array.length; i++) {
    if (array[i].itemName === item) {
      results = array[i].price
    }
  }
  return results;
}

Answer №1

Here is an alternative version of the lookup function you provided:

function searchPrice(arr, target) {
  for (let j = 0; j < arr.length; j++) {
    if (arr[j].product === target) {
      return arr[j].cost
    }
  }
  return "Item not found";
}

Answer №2

One way to approach this is by changing the logic as follows:

  • Rather than returning the price with a default value of 0, set it to null.
  • Scenario #1: If the item is found, return the actual price from the array.
  • Scenario #2: If the item is not found, return the price as null, and then you can easily check for that and set a default value like this:

    priceLookup(items, "abc") || "No item found with that name"
    

let items = [{itemName:"Effective Programming Habits",type:"book",price:13.99},{itemName:"Creation 3005",type:"computer",price:299.99},{itemName:"Finding Your Center",type:"book",price:15}];

function priceLookup(array, item) {
  let results = null;
  var foundItem = array.find(a => a.itemName === item);
  if (foundItem)
    results = foundItem.price;
  return results;
}

console.log( priceLookup(items, "Creation 3005") )
console.log( priceLookup(items, "abc") || "No item found with that name" )


Alternatively, you can achieve the same result with less code:

let items = [{itemName:"Effective Programming Habits",type:"book",price:13.99},{itemName:"Creation 3005",type:"computer",price:299.99},{itemName:"Finding Your Center",type:"book",price:15}];

function priceLookup(array, item) {
  return (array.find(a => a.itemName === item) || {}).price;
}

console.log( priceLookup(items, "Creation 3005") )
console.log( priceLookup(items, "abc") || "No item found with that name" )

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

Tips for transferring information from a C++ program to JavaScript

Currently, I am in the process of creating a jQuery-based pivot table for a desktop application using C++. The application will retrieve data from a database, pass it to an HTML page, and display it using a pivot table plugin. Since there is no web server ...

Guide to creating a unit test for canActivate guard in Angular routing

Seeking guidance on writing a unit test for angular routing with the canActivate guard. Encountering an error when using the guard on routes, but no error is thrown without it. Would appreciate a suitable example along with an explanation. app-routing.mod ...

Is it possible to save the video title as a variable using YTDL-core?

Is there a way to store the video title as a global variable in JavaScript? ytdl.getBasicInfo(videoURL, function(err, info) { console.log(info.title) }); I have been trying various methods but I am unable to successfully define a variable to hold the v ...

Show a visual content in Grails Server Pages created through a specific class

In my class file, I have the image path displayed as shown below: String val; val+= "<img src=/"PATH_TO_FILE/" alt=/"sometext/">" Now, I am attempting to load the image in a gsp view within a div using jQuery from the val variable. The image is be ...

Counting Clicks with the Button Counter

I'm having an issue with my jQuery code that is supposed to count button clicks - it stops after just one click. I need help fixing this problem. $(function() { $('.btn').click(function() { $(this).val(this.textContent + 1); }); } ...

Combine and total various multidimensional associative arrays

I'm looking for a solution to merge multiple arrays, each containing nested keys and values, and summing any duplicate keys or sub-keys that may exist. For instance: $arr1 = [ "Friday" => ["Breakfast" => 32, "Lunch& ...

What is the best method for debugging dynamically created routes in Express using debug statements?

Currently diving into an ongoing Node/Express/Mongoose project, I am unraveling the intricacies of the code to grasp its functionality. The dynamic generation of Express routes adds another layer of complexity, with functions setting up routes by passing i ...

After the file returns, my array structure spits out nonsense

I'm currently delving into the realm of the C language and my task involves reading lines from a file that include a name and a phone number. My goal is to dynamically allocate an array of structures and populate this array with the data extracted fro ...

What is the best way to apply color to individual polygons based on a specific parameter using javascript?

I attempted to customize the colors of polygons loaded from a geojson file on Google Maps based on the "population density" data. However, my script failed to execute as intended. I tried to extract the "population density" information within a loop funct ...

Dealing with JSON Stringify and parsing errors in AJAX

I've been troubleshooting this issue for hours, trying various suggestions found online, but I'm still encountering a problem. Whenever I encode function parameters using JSON.stringify and send them to my PHP handler through AJAX, I receive a pa ...

Ways to effectively manage multiple asynchronous operations while retrieving emails and attachments using IMAP and JavaScript

Currently, I am utilizing the IMAP library along with JavaScript to retrieve emails from a server. This is my approach: Retrieve emails based on email address, subject, and a specified time frame. Determine the total number of emails received. For each e ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

An issue arose when attempting to load the page using jQuery

Currently, I am implementing the slidedeck jquery plugin on my webpage to display slides. While everything is functioning properly, I am facing an issue with the CSS loading process. After these slides, I have an import statement for another page that retr ...

What is the reason for the Web worker creating a new Class Instance every time a module is imported?

We are currently running a time-consuming function on a web worker. In addition, we have a Dispatcher Class that creates a single instance for other classes to utilize, as shown below: class Dispatcher { constructor() { console.log("calling"); ...

Verify whether the value of the Object matches the value of the string

Currently, I have a situation in ES6 where I am utilizing Vue.js for the current module. The task at hand is to verify if a specific string value exists within an array object. let obj1 = [{name: "abc ced", id: 1}, {name: "holla' name", i ...

Tips for updating content (wishlist) without the need to refresh the page

Currently experimenting with the TMDb API to enhance my PHP skills. I've successfully created a wishlist feature and now looking to optimize the script. A function is implemented on each movie page for adding movies to the wishlist. function getButt ...

Exploring AngularJS: A closer look at ngOptions expressions

I have been struggling to populate a Select element with a list of objects for ngOptions. Despite confirming that the data structure is correct and accessible, I cannot get the Select to show the options. Even when rendering the options expression on the p ...

When the checkbox is unchecked

Is it possible to remove the Checkbox element from the array once it is unchecked? { columns.columnNames && columns.columnNames.map(el => { return ( <div> <input type="c ...

What could be the reason my span is not altering color as I scroll?

Important HTML Knowledge <section class="home" id="home"> <div class="max-width"> <div class="home-content"> <div class="text-1">Hey t ...

Assignments made to the 'toLoadNumber' variable within the React Hook useEffect will be reset after every re-render

I encountered an issue in the console related to the code snippet below: export const Contact = () => { useEffect(() => { // Code inside this block runs when the component mounts. return () => { // Code inside this block runs when the component ...