Guide on utilizing a variable as a property in the `indexOf` function within a `map` function

I have a method that looks like this:

retrieveUniqueValues(param) {
    var uniqueValues = [];
    uniqueValues = this.state.DataObjects.map(item => {
        if (uniqueValues.indexOf(item[param]) === -1) {
            uniqueValues.push(item[param])
        }
    });
}

//DataObjects is an array of objects

DataObjects = [
    {tag: 23, name: vicky, gender: m},
    {tag: 13, name: sam, gender: m},
    {tag: 23, name: raj, gender: m}
]

//item can be any object as shown above
item = {tag: 23, name: vicky, gender: m}

The param here represents the property name such as tag.

Even though the param has a value before and after the map function, I am encountering it as undefined in the following line:

if (uniqueValues.indexOf(item[param]) === -1) { }

My goal is to retrieve unique values for any specific property, for example, for the tag: 23, 13. While using x.tag or x.name or x.gender works fine, I intend to make the property name dynamic.

Answer №1

In order to dynamically search for the key that matches the value stored in param, you can make the following adjustment:

if (list.indexOf(obj.param) === -1) {
    list.push(obj.param)
}

Rather than searching for a key named param, you should update it to:

if (list.indexOf(obj[param]) === -1) {
    list.push(obj[param])
}

This change allows you to check for keys with names matching the value of param.

Answer №2

CollectionData = [
    {id: 23, title: 'apple', category: 'fruit'},
    {id: 13, title: 'banana', category: 'fruit'},
    {id: 30, title: 'orange', category: 'fruit'}
]
output = _.map(CollectionData,'id'); //[23, 13, 30], check if ID exists in the array!
if(output.indexOf(23)===-1)
    outcome = 'missing';
else 
    outcome = 'present';

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

Encountering a type error when attempting to assign an interface to a property

In my Angular project, I am working with typescript and trying to assign the IInfoPage interface to some data. export interface IInfoPage { href: string; icon: string; routing: boolean; order: number; styleType: string; ...

The button labeled "modify layout" remains unresponsive when activated

Allow me to start by saying that I am not a coding expert. Currently, I am enrolled in a computer science class and have a basic understanding of HTML, CSS, and some Javascript. However, I have encountered a problem that I cannot solve. When I click on th ...

Converting numbers in React Native, leaving only the last four digits untouched

When mapping biomatricData.ninId, the value I am receiving is "43445567665". biomatricData.ninId = 43445567665 My task now is to display only the last 4 digits and replace the rest with "*". I need to format 43445567665 as follows: Like - *******7665 ...

Is there a way to retrieve the intersection point (Vector3) of the intersectObjects?

I need assistance in finding the point where a ray cast from 'child' intersects with a mesh (child2) using Raycaster: var raycaster = new THREE.Raycaster(); var meshList = []; meshList.push(child2); for (var i = 0; i < child.geometry.vertices ...

How to italicize a portion of output using JavaScript

There are numerous inquiries on the internet and on this site regarding how to make italic fonts, however, none specifically address how to italicize only a section of a string. In my scenario, I have a form where I input the book title, author's nam ...

`Is there a way to effectively test an @Input component in Angular?`

Despite multiple successful attempts in the past, I am facing some difficulty getting this to function properly. Within my component, I have an input @Input data: Data, which is used in my template to conditionally display certain content. Oddly enough, du ...

What is the best way to trigger a javascript modal to open automatically after a specific duration

Let's take an instance where my modal has the ID #modal1. It usually appears through a button-based action. ...

"Discovering the method to showcase content based on page number or when the 'previous' or 'next'

Here is how my Vue component looks like: <template> ... <b-col v-for="item in items" v-bind:key="item.id" cols="2"> ... <strong slot="header" class="text-dark" :title ...

Troubleshooting issue with Bootstrap collapse functionality failing with dynamic IDs

Having trouble creating dynamic ids for bootstrap collapsing functionality. I want each topic in an ng-repeat to collapse and display its respective question list when clicked. The issue is that when I click on a second topic, the question list data from ...

The `$(this).data()` function removes any excess data from a database, stopping at the first occurrence of a

One issue I am encountering is when retrieving data with a whitespace. I need the complete string of data, not the trimmed version. When retrieving "data-title" or "data-type", the data gets cut at the whitespace. I tested by setting a static string in ...

Transmitting a Custom JS Object via Vue Router

Stuck! I’ve been hitting my head against the wall for hours trying to figure this out... Technologies Utilized: Vue (v3.0.0) Vue-Router (v4.0.0-0) Bootstrap (v5.1.1) The Objective: I have two pages (Home.vue, MetaUpdate.vue) and one component (Docum ...

The AJAX function fails to trigger the MVC controller method

I'm attempting to enable inline editing by cell, rather than by row, when double-clicking. Although the initial setup is working, it's not updating the record as expected - the "SaveCustomer" call to the controller isn't triggered. Can anyon ...

Optimize your mobile experience by creating a notification menu that is scrollable and fixed in position

Recently, I purchased Moltran, but encountered a major issue: The notification menu disappears on mobile devices, which is not ideal for me. After some research, I discovered that removing the hidden-xs class from the li notification element can solve this ...

Step-by-step guide on how to prioritize rendering the login page before the ngView in AngularJS in order to

As I begin my journey with Angular JS, I am eager to implement security measures in my application. My intention is to set up a log-in page as the default landing page for my single page application. Can anyone provide guidance or recommendations on how ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

After the ajax request is made in React JS, the column vanishes from the screen

Upon querying a node.js server's PostgreSQL database, I receive specific data that needs to be displayed in two separate tables. Each table consists of two columns. However, after the AJAX call, only the first column is being populated in the first ta ...

Making a Connection with Ajax in Django: Adding Friends

I have been exploring the capabilities of Django-Friends My goal is to make it so that when a user clicks on the add friend button, it either disappears or changes to say "Request sent". However, I am encountering an issue where the button does not disapp ...

The 'wrapper' property is not present in the 'ClassNameMap<never>' type in Typescript

Hey there, I've been encountering a puzzling issue in my .tsx file where it's claiming that the wrapper doesn't exist. My project involves Material UI and Typescript, and I'm relatively new to working with Typescript as well as transiti ...

What could be causing the queuing of multiple Ajax requests in ExtJS?

I am encountering an issue with my grid setup. I have a menu on the left side for each item on the grid, and this menu's items change based on the selection in the grid. When the event selection is triggered, an Ajax.request function is called to hand ...

What is the best way to assign Reference Identification numbers to the orders?

Is there a way for me to obtain and attach the id reference to the order? I have retrieved the product and user ids. When I utilize my get method, it should retrieve all the details about the products and users. For instance, the data will display compreh ...