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

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...

Step-by-step guide on incorporating a hyperlink within a row using @material-ui/data-grid

I am currently using @material-ui/data-grid to showcase some data on my webpage. Each row in the grid must have a link that leads to the next page when clicked. I have all the necessary data ready to be passed, however, I am facing difficulty in creating a ...

Is there a way to dynamically pass values to a form in React?

Learning React on my own has been challenging, especially when trying to accomplish what I thought would be a simple task. To put it briefly, I have a menu with several items. I aim to select a menu item and have a form open next to it. The form shoul ...

Why does it display 'Undefined' when I attempt to access an object in an array in Next.js?

I am currently working on a way to display sub Products related to the main product. I have attempted to extract the product code from the URL and then retrieve sub-products that correspond to the main product code. List of Products and Sub products const ...

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...

Implement jQuery Tabs in Brackets software to enhance user experience

My Adobe Creative Cloud subscription is expiring soon, and I am considering switching to Brackets, an open-source code editor developed by Adobe. However, I am facing some difficulties adding jQuery tabs to my HTML documents. I downloaded the 1.10.4 zip f ...

Updating a React event as it changes with each onChange event

Let's address a disclaimer before diving into the issue - for a quick look, visit this pen and type something there. The Scenario This is the JSX code snippet used in my render method: <input value={this.state.value} onChange={this.handleCh ...

The e2e Protractor test is unable to identify the Angular component within a complex Angular router with multiple layers

I am currently working on an Angular application and I need to set up end-to-end testing for this project. Angular Package: 4.6.6 Protractor: 5.3.0 In addition, my project includes a multi-layer router that wraps the router-outlet into another component ...

Tips for choosing elements in JavaScript using querySelector even after they've been included in the code using innerHTML

Within the scenario below, a parent element is present in the HTML code and the span element with a class of 'child' is nested within the parent element using the createChild function. Subsequently, the content of the child element is modified el ...

Updating the dynamic site script to be compatible with the newest version of the jQuery library

After finding a script on http://css-tricks.com/dynamic-page-replacing-content/, I decided to edit it to suit my needs. Initially, everything worked perfectly with "jquery-1.4.4". However, when I tried using versions later than "jquery-1.5", the active cla ...

What are the steps for adding node packages to sublime text?

Is there a way to install node packages directly from Sublime Text instead of using the command line? If so, what is the process for doing this? I'm not referring to Package Control; I'm specifically interested in installing npm packages like th ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Creating a message sniping command with Discord.js

I'm having trouble getting my bot to log/snipe a message when someone says 'zsnipe'. I want to make 'zsnipe' a command, but it's not working. Could you let me know what I'm doing wrong? Here is the code snippet: bo ...

Is the CSS scale activated by mouseover or click?

My CSS code successfully scales images, but the issue is that it affects every image on the page. I am looking for a solution to apply this CSS only when the user hovers over or clicks on an image. The challenge is that images are added by non-technical w ...

Explore the full range of events available on the Angular UI-Calendar, the innovative directive designed for Arshaw FullCalendar

Utilizing external events with Angular ui-calendar: HTML: <div id='external-events'> <ul> <li class='fc-event'>Event 1</li> <li class='fc-event'>Event 2< ...

Show the last polygon that was created using OpenLayers on the screen

Using this example from OpenLayers website: I am attempting to create a polygon but I would like it to vanish once the polygon is finished. Could anyone offer assistance with this? Thank you :) ...

The importance of adding ".$" to an AngularJS filter object

I have been exploring a section of code related to filtering in AngularJS from the documentation website. (cf. http://docs.angularjs.org/api/ng.filter:filter) Specifically, I am curious about the use of .$ appended to the object search, as shown in the fo ...

Having trouble with running 'npm init -y' in Windows? Here's a workaround for the VS

An error occurred when trying to initialize npm with the command "npm init -y". The name "WEB DEV" was deemed invalid. For a detailed log of this issue, please refer to: C:\Users\User\AppData\Roaming\npm-cache_logs\2020-12-05 ...