Contrasting an array of items with an array of Objects

I need to match the values in an array called ingredientName with a corresponding array of objects. Here is how they look:

const ingredientName = ['chicken', 'cheese', 'tomato', 'lettuce'];

let imageObjects = [
  {
    name: 'chicken',
    image: "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg"
  },
  {
    name: 'cheese',
    image: "https://spoonacular.com/cdn/ingredients_100x100/cheddar-cheese.png"
  },
  {
    name: 'tomato',
    image: "https://spoonacular.com/cdn/ingredients_100x100/tomato.png"
  },
  {
    name: 'lettuce',
    image: "https://spoonacular.com/cdn/ingredients_100x100/iceberg-lettuce.jpg"
  },
];

The goal is to retrieve the image associated with each ingredient from ImageObjects.

const generateDishes = () => {

  for (let i = 0; i < ingredientName.length; i++) {
    for (let j = 0; j < imageObjects.length; j++) {
        if (ingredientName[i] == imageObjects[j].name) {
            const newImage = $('<img>').attr('src', imageObjects[j].image)
            $('#dishRect1').append(newImage)
        }
    }

  }
};

Answer №1

Here's one way to accomplish it:

const ingredientList = ["beef", "cheese", "tomato", "onion"];

let imageBank = [{
    name: "beef",
    image: "https://example.com/beef.jpg",
  },
  {
    name: "cheese",
    image: "https://example.com/cheese.png",
  },
  {
    name: "tomato",
    image: "https://example.com/tomato.png",
  },
  {
    name: "onion",
    image: "https://example.com/onion.jpg",
  },
];


let ingredientImages = ingredientList.map((ingredient) =>
  imageBank.find((image) => image.name === ingredient).image
);

console.log(ingredientImages)

Answer №2

Utilize a different item from the image Objects by using gradientName as the key.

const ingredientName = ['chicken', 'cheese', 'tomato', 'lettuce'];

let imageObjects = [ { name: 'chicken', image: "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg" }, { name: 'cheese', image: "https://spoonacular.com/cdn/ingredients_100x100/cheddar-cheese.png" }, { name: 'tomato', image: "https://spoonacular.com/cdn/ingredients_100x100/tomato.png" }, { name: 'lettuce', image: "https://spoonacular.com/cdn/ingredients_100x100/iceberg-lettuce.jpg" }, ];

let imageMap = imageObjects.reduce((agg, {name, image})=>{
  return {...agg, [name]: image}
},{})

Implement iteration with O(n) time complexity now.

for (let i = 0; i < ingredientName.length; i++) {
     const newImage = $('<img>').attr('src', imageMap[ingredientName[i]])
    $('#dishRect1').append(newImage)

}

Answer №3

Give this a shot:

const itemNames = ['apple', 'banana', 'grape', 'orange'];

let itemImages = [
  {
    name: 'apple',
    image: "https://example.com/apple.jpg"
  },
  {
    name: 'banana',
    image: "https://example.com/banana.png"
  },
  {
    name: 'grape',
    image: "https://example.com/grape.png"
  },  
  {
    name: 'orange',
    image: "https://example.com/orange.jpg"
  },
];

result=itemImages.filter(({name})=> itemNames.includes(name)).map((elem)=> elem.image);
console.log(result);

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

Identify whether the application is built with nextJS, react, or react-native

I'm currently developing a library for React applications and I anticipate that certain features will function differently depending on the environment. I am seeking a method to identify whether the current environment is a ReactJS application (creat ...

Guide on linking JavaScript files in Node.js

I am having trouble getting my javascript to work properly. My javascript files are located in the public/javascripts directory. app.js app.use(express.static(path.join(__dirname, 'public'))); views/layout.pug doctype html html head ti ...

Creating a dynamic object for a React component by utilizing props

I currently have a component that displays a grid of 6 items. These items are hard-coded as gridItems. My goal is to make this component dynamic by allowing it to render specific items based on props passed to it. Instead of always displaying 6 items, I ...

(node:19502) UnresolvedPromiseRejectionNotification: Promise rejection not handled (rejection id: 1): TypeError: Unable to access property 'indexOf' of undefined

I successfully integrated cucumber with nightwatch.js. Here is a snippet of my package.json file: { "name": "learning-nightwatch", "version": "1.0.0", "description": "learning nightwatch", "license": "UNLICENSED", "scripts": { "nightwatch": ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Serve different files using Node.js socket.io webserver, not just index.html

I recently started delving into socket.io and decided to use this chat example as a reference. As I navigate to ip:8080/public/index.html, I realize the need to access other files, such as additional JS scripts that will be used on the client side in the ...

Experimenting with the speechSynthesis API within an iOS webview application

I'm currently working on developing an app that features TTS capabilities. Within my webview app (utilizing a React frontend compiled with Cordova, but considering transitioning to React Native), I am implementing the speechSynthesis API. It function ...

Attempting to organize date and time down to the second

I'm currently working on sorting time with seconds included. While I am able to sort the minutes successfully, I'm facing difficulty in sorting the seconds. Despite trying various approaches and using dynamic data that needs to be sorted in desce ...

Sending JSON Data over URL

I am facing a challenge with passing data between two HTML files. My initial solution involved sending the data through the URL using the hash and then parsing the link using JSON.parse(window.location.hash.slice(1));. This method worked for a few attempts ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

BOOTSTRAP: changing the layout of panels in various sizes for mobile devices

I'm struggling with how to reorganize my panels on mobile devices. Each panel has a different size. Please refer to the attached screenshot for the page layout on large screens (col-lg): https://i.sstatic.net/xcqaT.png EDIT: The layout on large scre ...

Incorporate VLC player into a webpage without any visible control options

Is there a way to embed a flash video in a webpage without showing any controls? I managed to embed a flash video using VLC with the following code: <embed src="img/Wildlife.wmv" height="480" width="640"> However, I want the video to play without ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Ensuring the checkbox is disabled prior to editing

Check out my table below: https://i.stack.imgur.com/7byIa.png Whenever I click the edit button, I can modify the status field and action field. This feature works correctly. However, the issue is that I am able to change the values of status and action e ...

I am interested in retrieving an array

Here is the array I am working with { Colors: 'Blues', Department: 'Clearance', Size: [ 'Runners', 'Custom Sizes' ], Shape: 'Round', Designer: 'B. Smit', } The desired output should be ...

Unable to Retrieve JSON Output

PHP Code: $contents = ''; $dataarray = file('/location/'.$_GET['playlist'].''); //Loading file data into array $finallist = ''; //Extract Track Info foreach ($dataarray as $line_num => $line) //Loopin ...

Maintaining TextBox State in ASP.Net Through Postbacks

Can anyone help me figure out how to maintain the control state that has been modified in Javascript? I am working with two TextBoxes, one DropDownList, and a button (all Runat=Server) in C# ASP.net 2010 Express. The first textbox accepts any user in ...

What is the best way to start the server when the files are located in separate directories?

I have organized my project into two separate folders, one for the client and one for the server Is there a way to use npm start to simultaneously run both the frontend and backend scripts? Check out the screenshot below: View of Two Folders in my Projec ...

What is the best way to integrate a Next.js Image component with a set width and an adaptable height in order to maintain the image's proportions?

This code snippet uses ChakraUI styling and retrieves images from SanityCMS: <Box w="500px" h="500px" bg="red"> <Image src={allArtPieces[0].imageUrl} alt={allArtPieces[0].title} width="500px" ...