What is the most effective way to retrieve the slug value from an array of objects that matches a given id?

I am currently working on extracting the slug value from an array within the object.extra.services. The goal is to find the element in this array that matches the ID I provide...

// Service ID provided
const serviceID = '5cdd7c55f5abb90a689a44be';

// Array of services Ids
getProductsServices(products) {
      const productsServices = [
        ...new Set(products.map(product => product.extra.services))
      ];
      const productsList = [].concat.apply([], productsServices);
      return productsList;
    },

// ServiceId Matching
serviceMatch(serviceID) {
      return this.getProductsServices.includes(serviceID);
    }

Now, I need to retrieve the slug value from the array that corresponds to the provided service ID.

products [{
    "_id" : ObjectId("5e0257dcbe760674b10d4122"),
    "desc" : "Website Design",
    "extra" : {
        "image" : "/2018/06/design-of-logos-for-companies.jpg",
        "services" : [ 
            "5cdd7c55f5abb90a689a44be", 
            "5cdd7c55f5abb90a689a3fcc", 
            "5cdd7c55f5abb90a689a3f42"
        ]
    },
    "name" : "Logo Design",
    "slug" : "online-logo-design"
},
{
    "_id" : ObjectId("5e0257dcbe760674b10d4122"),
    "desc" : "Logo Design",
    "extra" : {
        "image" : "/2018/06/design-of-logos-for-companies.jpg",
        "services" : [ 
            "5cdd7c55f5abb90a689a44be", 
            "5cdd7c55f5abb90a689a3fcc", 
            "5cdd7c55f5abb90a689a3f42"
        ]
    },
    "name" : "Logo Design",
    "slug" : "online-logo-design"
},
{
    "_id" : ObjectId("5e0257dcbe760674b10d4122"),
    "desc" : "Interior Design",
    "extra" : {
        "image" : "/2018/06/design-of-logos-for-companies.jpg",
        "services" : [ 
            "5cdd7c55f5abb90a689a44be", 
            "5cdd7c55f5abb90a689a3fcc", 
            "5cdd7c55f5abb90a689a3f42"
        ]
    },
    "name" : "Logo Design",
    "slug" : "online-logo-design"
}]

Answer №1

Utilize the includes method:

const result = items.find(item => item.features.includes("5cdd7c55f5abb90a689a3fcc"))
if (result) {
  console.log('Item found:', result)
}

Answer №2

My interpretation is that this can be accomplished by utilizing a combination of find in conjunction with some:

let desiredProduct = productArray.find(product => product.features.some(id => id === desiredFeatureId));
console.log(desiredProduct.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

How can I link a textarea to a POST request in React?

Is there a method to link the textarea with my POST request in order to modify values and transmit the data as .json? ...

Organizing the date string in the format of day-month-year (DD-MM-yyyy) with the

Here is a function that needs sorting in descending order: listOfTransactions.map(({ tdate='', out='', in='' }) => { return { date: '10 Feb 2022', out: 'AAA in: 'BBB' } }) // The function r ...

Analyzing various array values to modify the status of a table

In the case of three records, the goal is to compare the values of 'test1' and 'test2' and then update the database to either 'open' or 'close' if the 'test1' and 'test2' values of the three recor ...

Understanding the reactivity and data management in Vue.js through the use of mixins

I am attempting to create a toggle flag that can switch between boolean values of true and false based on specific conditions. // main.js new Vue({ el: `#app`, render: h => h(App,{ props:{ todoID: this.dataset.id } }) } ...

What are the steps to ensure that $.getScript functions properly?

It seems like the $.getScript function in jQuery will be really helpful once it's functioning properly, but I'm having some trouble with the last part. I have a feeling that the issue is related to how I'm loading JS files. How can I resolve ...

Techniques for transferring information to Highchart directly from session storage

I am attempting to populate a pie highchart with data from a session storage variable, but I am not seeing any results. Here is the desired code: $(function () { Highcharts.chart('container', { chart: { type: 'pie', ...

Error: React unable to access the 'title' property as it is undefined

I'm trying to access an array from the state in my App Component, but for some reason it's not working. import React from "react"; import "./App.css"; //import Category from "./components/Category"; class App extends React.Component { const ...

Troublesome issue with Three.js cubeCamera and envmap functionality not functioning

Hello, I am currently facing two issues with the cubecamera in the three.js plugin. Every time I try to set up a cubecamera, cubeCamera = new THREE.CubeCamera( 1, 100000, 256, 128 ); //cubeCamera.renderTarget.minFilter = THREE.LinearMipMapLinearFilter; c ...

`Can someone provide instructions for eliminating HTML entities from JSON data?`

Currently, I am developing an RSS feed application using AngularJS with JSON data as a base. You can check out the progress here. So far, I have successfully extracted the post titles and content. However, I encountered an issue while handling the content ...

Guide for accessing elements of arrays within an array in Dart and Flutter

I am currently working on developing a Flutter application that responds to voice commands by displaying specific text based on the command given. To achieve this, I have defined a class called Command which contains an array of commands categorized into t ...

What is the process for preserving changes made in rest_in_place when inputting a new type?

In my rails project, I've implemented the rest_in_place plugin to enable dynamic data editing. <ul class="offer-completed__edit-details" data-url="<%= enquiry_path(@enquiry) %>" data-object="enquiry"> <li>Contact Name: <span ...

Passing a PHP array to a JavaScript function using a button click event in an HTML form

It seems there was some confusion in my approach. I'm working with a datatable that has an edit button at the end. Clicking on this button opens a modal, and I want to pass the data from the table to the modal. While I can send it as a single variabl ...

Unexpected error in Jquery

NOTE* Although there is a similar question about this issue, it pertains to another user's problem. I am seeking a way to delve deeper into this error and identify the root cause. I keep encountering this Type Error: Uncaught TypeError: ((x.event.sp ...

What is the reason for placing a ReactJS component, defined as a function, within tags when using the ReactDom.render() method?

As someone who is brand new to ReactJS and JavaScript, I am struggling to grasp the syntax. The component I have created is very basic: import React from 'react' import ReactDom from 'react-dom' function Greetings() { return <h1&g ...

HTML Action Identifier using the GET method

There is a possibility that this question may be a duplicate, but I am unable to locate the original. Within my form, there is an action: <form id="bug-form" action="/AST_14/Bugg.ly2/index.php/bug/update/" method="post"> The process in my system i ...

What is the method for obtaining a Boolean value that exists in mongoose?

I'm currently attempting to verify if an account associated with the same username already exists. However, when utilizing the exist method for checking, I'm receiving a large object instead of a Boolean value. async checkExisting(username,userCo ...

Displaying local time alongside global time using PHP

I have a challenge - I am storing time in DATETIME format and now I need to display it in the local timezone. Does anyone know how to achieve this using PHP? ...

Tips for utilizing the form.checkValidity() method in HTML:

While delving into the source code of a website utilizing MVC architecture, I encountered some difficulties comprehending it fully. Here is a snippet of the view's code: function submitForm (action) { var forms = document.getElementById('form& ...

Storing data in variables from a single div using Javascript

Within a div element, there lies a number that undergoes constant changes. An example of this is: <div id="current">124</div> A JavaScript function has been implemented to retrieve the data from this specific field and store it in a JavaScrip ...

Tips for configuring Windows WebStorm to properly import a Linux Vue webpack project

After installing WebStorm on my Windows desktop, I proceeded to install Vue on Linux with the following commands: $ npm install -g vue-cli $ vue init webpack vuedemo $ npm install $ npm run dev Now I am wondering if there is a way to use WebStorm on my W ...