Discovering a specific value by locating a string in an array nested inside an object

Here is an example object that I need help searching:

data = [
  {
    type: "fruit",
    basket: ["apple", "pear", "orange"]
  },
  {
    type: "vegetable",
    basket: ["carrot", "potato"]
  }
];

I am trying to find the item 'potato' and return its corresponding type, which should be 'vegetable'. I have been attempting to use filter or map in vanilla JavaScript, but I am struggling with the syntax. Can you provide me with a solution?

Answer №1

One possible solution is displayed below:

let result = data.map(
    item => item.basket.indexOf("potato") === -1 ? undefined : item.type
).filter(item => item !== undefined);

The variable result will contain a list of all matching types (there may be multiple matches if the same value appears more than once in the dataset). You can access the first matched type by using result[0]. If you are certain that the values are unique, this will return either the type value or undefined if it is not found.

Answer №2

If you're looking for a solution, you can utilize the Array#find method in combination with Array#includes.

var data = [{ type: "fruit", basket: ["apple", "pear", "orange"] }, { type: "vegetable", basket: ["carrot", "potato"] }],
    find = 'potato';

console.log(data.find(o => o.basket.includes(find)).type);

Answer №3

Utilize the Array#find method to loop through each object and employ either Array#some or Array#includes to iterate through each basket and validate if there is an item named potato.

const data = [
  {
    type: "fruit",
    basket: ["apple", "pear", "orange"]
  },
  {
    type: "vegetable",
    basket: ["carrot", "potato"]
  }
];

const itemWithSome = data.find(item => item.basket.some(i => i === 'potato'));

console.log(itemWithSome.type);

const itemWithIncludes = data.find(item => item.basket.includes('potato'));

console.log(itemWithIncludes.type);

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

Having trouble with the jQuery .addClass function failing to add a class?

I'm struggling to implement a highlighting feature for specific elements on my website. I've been utilizing the jQuery("selector").addClass("class") function, but it's not functioning as expected. function toggleHighlight(selector, on) { ...

Tips for gathering structs in an ELF section with gcc compiler __attributes__?

This question is related to the previously accepted answer found in this particular Stack Overflow post. I believe this topic deserves further exploration, hence why I am presenting it here. My objective is to gather structs defined across different modul ...

Generating a JSON object using HTML select elements

Looking to generate a JSON string that includes select values and inner HTML values in a map format. For example: <select id="my-select"> <option value="1">one</option> <option value="2">two</option> </select> var json ...

A unique Javascript feature that switches the text on various buttons

As someone who is relatively new to Javascript and web development, I am currently working on a project that involves creating multiple text areas for users to input and save text. Each text area is accompanied by a button with a unique ID that functions a ...

Is there a way to deactivate a button in Angular when an <input> field is blank, without relying on form validation?

Looking for a way to utilize @output in Angular, I have set up an input field with a button. The goal is to send the input field data to the parent component using @output(). My challenge is to disable the button if the input field is empty, without relyin ...

What are the best techniques for organizing SCSS in Next.js?

There are multiple pages with some unused items. Is there a method to search and delete all the items based on their classname? Appreciate any assistance you can provide! ...

How can I create a hover effect animation in React?

I am looking to replicate the menu item underline animation demonstrated in this example. In jQuery, I would easily achieve this by obtaining the left position and width of a menu item, then using stop.animation on hover. Attempting this animation with R ...

Utilizing a fallback option for HTML5 video with a flash player and the ability to manipulate the

My dilemma involves an HTML5 video where I am utilizing jquery to interact with the player using the code snippet: video.currentTime += 1;. However, when Internet Explorer switches to Flash plugins, my JQ commands cease to function. How can I manage and co ...

Adobe Acrobat does not run JavaScript code in documents that are submitted for electronic signatures

Lately, I have been experiencing issues with pdfs that contain embedded javascript. The strange thing is that the javascript functions perfectly in the Acrobat Pro DC app but fails to execute when the document is sent for signature. To troubleshoot, I cre ...

Facing issues with Laravel errors preventing the implementation of CSS on my localhost

These are the tailwindcss errors I am encountering: npm WARN @tailwindcss/[email protected] requires a peer of tailwindcss@^1.0 but none is installed. You must install peer dependencies yourself. npm WARN @tailwindcss/[email protected] requi ...

Using Node.js to schedule and send notifications to a specific topic via FCM

In order to deliver topic notifications to Android devices using FCM, I have set up an Angular application and a Node.js server. The scheduling of these notifications is handled by the bull library. The process involves two methods of sending notification ...

Getting your routing to function properly in React.js involves setting up routes for different

I have been working on a React project, which can be found here, and trying to tackle the issue of relative links in the navbar. However, every time I click on About Me, I encounter this message: Cannot GET /about The chunk of code I am currently dealing ...

Adding a newline character ( ) to each element in the array before converting

Why, when I use JSON.stringify, is appending to the value? Take a look at this example link: http://jsfiddle.net/7nketLmy/ var formData = new Array(); if ($(this).get(0).tagName.toUpperCase() === 'DIV' ){ content = $(this).html(); ...

Stopping an HTML5 range input at a specific number: Tips and tricks

Does anyone have suggestions on how to use angularjs to stop a range slider at 75? I attempted it but it doesn't seem like the best approach. Any guidance would be appreciated. [EDIT for clarification after max=75 answer] Just to clarify, I want to di ...

Display jQuery created hyperlinks in a modal window

I have taken on the task of revamping my school's outdated website. Please excuse the messy CSS and HTML as I am currently in the process of cleaning it up. Additionally, I am not well-versed in Javascript, so... Now, onto the issue at hand. The web ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

What is the process for incorporating TypeScript typings into a snippet of jQuery code designed for a Bootstrap multilevel dropdown menu?

I'm exploring Angular for the first time and trying to create a multi-level dropdown using Bootstrap. I came across this article which contains some JavaScript code snippets that I am struggling with. I need help converting this code into TypeScript, ...

Personalizing MaterialUI's autocomplete functionality

Trying to implement the material-UI Autocomplete component in my react app and looking for a way to display a div when hovering over an option from the list, similar to what is shown in this reference image. View example If anyone has any tips or suggest ...

Guide on saving the token in local storage or cookies to grant access to specific web pages for users

Currently, I am in the process of developing an authentication system using Node.js, MySQL, and Express. Initially, I focused on saving and verifying user credentials in the database. Recently, I incorporated JWT (JSON Web Token) into the system. My next s ...

Tips for updating the state of a component within the SignalR connection.on() method

Trying to pull data from the server using SignalR and update a React component, everything appears fine. The data is successfully received from the server, BUT the state of the component remains undefined. Take a look at the code snippet below: import Re ...