What is the best way to identify the property of an object that holds a specific value?

Searching through an object array in JavaScript to find a specific value and identify the property containing that value is my current task. Here's an example:

Object Array:

var objArray = [{
    "ID": 1,
    "Name": "Kathy",
    "Position": "Programer",
    "Hobbies": "Computers",
    "Car": "Mustang"
  },
  {
    "ID": 2,
    "Name": "John",
    "Position": "Programing",
    "Hobbies": "Fishing",
    "Car": "Ferrari"
  },
  {
    "ID": 3,
    "Name": "John",
    "Position": "Sales",
    "Hobbies": "Programing",
    "Car": "Audi"
  },
  {
    "ID": 4,
    "Name": "William",
    "Position": "Marketing",
    "Hobbies": "Movies",
    "Car": "Corvette"
  },
  {
    "ID": 5,
    "Name": "Stephanie",
    "Position": "Director",
    "Hobbies": "Jogging",
    "Car": "Ferrari"
  }
];

If I want to locate any values that contain Program:

JavaScript:

function findMe(array, value) {
  var results = [];
  for (var i = 0; i < array.length; i++) {
    if (String(Object.values(array[i])).indexOf(value) >= 0) {
      results.push(array[i]);
    }
  }
  return results;
}

var obj = findMe(objArray, 'Program');

The function successfully populates obj with all entries containing the substring Program.

However, I now face the challenge of determining which property within the array holds the identified value.

In this scenario: The properties Position and Hobbies both contain the value Program.

Answer №1

Begin by breaking it down a bit with the addition of a function that can find a specific substring within an object's values.

Subsequently, coding challenges often revolve around clearly defining the expected output. How about proposing this as a potential specification: Generate an array based on the input array. This resulting array will consist of -- for each object in the input -- an array of keys where a specified string is found as a substring.

// identify keys in objects containing specified substring in their string values
function propertiesContainingSubstring(object, sub) {
    return Object.keys(object).filter(key => {
        let value = object[key];
        return (typeof value === 'string') && (value.indexOf(sub) >= 0);
    });
}

// produce an array of arrays. Each inner array comprises keys in the source array's
// objects where the specified value is present as a substring in the objects' values

function searchForMe(array, value) {
    return array.map(object => propertiesContainingSubstring(object, value));
}

var objArray = [{
    "ID": 1,
    "Name": "Kathy",
    "Position": "Programer",
    "Hobbies": "Computers",
    "Car": "Mustang"
  },
  {
    "ID": 2,
    "Name": "John",
    "Position": "Programing",
    "Hobbies": "Fishing",
    "Car": "Ferrari"
  },
  {
    "ID": 3,
    "Name": "John",
    "Position": "Sales",
    "Hobbies": "Programing",
    "Car": "Audi"
  },
  {
    "ID": 4,
    "Name": "William",
    "Position": "Marketing",
    "Hobbies": "Movies",
    "Car": "Corvette"
  },
  {
    "ID": 5,
    "Name": "Stephanie",
    "Position": "Director",
    "Hobbies": "Jogging",
    "Car": "Ferrari"
  }
];

console.log(searchForMe(objArray,"Program"));

Answer №2

I'm facing an issue where I need to identify which property of the array holds a specific value. How can I achieve this?

Here is a solution that may meet your requirements:

var objArray = [{
    "ID": 1,
    "Name": "Kathy",
    "Position": "Programer",
    "Hobbies": "Computers",
    "Car": "Mustang"
},
{
    "ID": 2,
    "Name": "John",
    "Position": "Programing",
    "Hobbies": "Fishing",
    "Car": "Ferrari"
},
{
    "ID": 3,
    "Name": "John",
    "Position": "Sales",
    "Hobbies": "Programing",
    "Car": "Audi"
},
{
    "ID": 4,
    "Name": "William",
    "Position": "Marketing",
    "Hobbies": "Movies",
    "Car": "Corvette"
},
{
    "ID": 5,
    "Name": "Stephanie",
    "Position": "Director",
    "Hobbies": "Jogging",
    "Car": "Ferrari"
}];

var foundObjects = [];

for(var i = 0; i < objArray.length; i++)
    for(var j in objArray[i])
    {
        if((''+objArray[i][j]).indexOf('Program') >= 0)
            foundObjects.push({objIndex: i, propertyIndex: j});
    }


for(i = 0; i < foundObjects.length; i++)
{
    var obj = foundObjects[i];
    console.log('Word "Program" was found by object with index: ' + obj.objIndex + ' in the property: ' + obj.propertyIndex);

}

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

Similar to the filter() method in Vanilla Javascript but behaves in a equivalent way to

Looking to convert some JQuery code to Vanilla JS. $('#myID :not(a, span)').contents().filter( function() { return this.nodeType === 3 && this.data.trim().length > 0;}) .wrap('<span class="mySpanClass" />'); I&a ...

Tips for executing multiple commands in NodeJS using child_process.exec

NOTE: I checked this question but it didn't provide the answer I needed. In my attempt to design a task runner for Atom, I encountered difficulties when trying to execute multi-line shell scripts. The issue arose when executing the following code: co ...

Displaying a loading template within an Angular component

While reviewing some code in AngularJS version 1.2.22, I came across the following snippet in the HTML: <div class="mainContent" ng-include="content"> </div> Within its corresponding controller, I found this: $scope.content = 'templates ...

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

The Router.use() function is looking for a middleware function, but instead received an undefined value at the

Currently, I am working on implementing authentication with node.js following a tutorial. However, I have encountered some issues that I am struggling to resolve. This is how I have configured the server: // Inserted code for configuring the server The ...

Fixing perspective clipping in Three.js

In my Three.js project, I have a plane inside a sphere that I am applying a shader to in order to achieve certain visual effects on the sphere. To ensure that the plane is always facing the camera, I am using the lookAt method. However, I have noticed that ...

Guide to making a template-based multi-dimensional std::array in C++:

Is it possible to create a multi-dimensional std::array of type Type with known initial constexpr dimensions using smart variadic templates for an "MDA"? The number of dimensions should be variable. I envision being able to write: MDA<int,3,4,5,6> ...

Creating Docker images in a lerna monorepo without the need for publishing

In the context of Lerna monorepos, the primary goal is to facilitate branch building and deployments. The challenge arises from the fact that Lerna monorepos either consolidate dependencies in NPM or utilize yarn workspaces to achieve the same outcome, re ...

I am having trouble retrieving the properties of "2d" objects using tiles[i-1], unlike standard objects in JavaScript

I've been working on constructing a random map generator by utilizing a grid composed of tiles within a canvas. In my process, I'm investigating the properties of each tile tiles[i] before handling tiles[i-1]. While this procedure seems to functi ...

The function causes an unexpected alteration in the coordinates of polygons on a leaflet map

I have been working on enhancing the functionality of a leaflet map by adding triangles with specific rotations to each marker that is created. The code snippet below demonstrates how I achieve this: function add_items_to_map( to_map, longitude, latitude, ...

Populate a bootstrap-select dropdown menu with an array of choices

After creating a table using datatables and adding an empty dropdown select on the footer with Bootstrap-select, here is the code snippet: <tfoot> <tr> <th><select class="selectpicker" multiple></select>< ...

What is the best way to apply a class to an element in an input template using Angular's ngFocus directive, or any directive incorporated in the Ionic Framework?

I'm working with a template that looks like this: <label class="item item-input" ng-class="{'focus':authData.username.focus}"> <--add class here if input:focus <span class="input-label">Username</spa ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

Troubleshooting: Issues with jQuery.on method functionality

I'm currently using jQuery version 1.9.1 and I have a situation where I need to perform an action on a dynamically added td element. I attempted to utilize the jQuery.on function, however my code is not being triggered. Can someone please provide some ...

Dynamically hiding elements within tabs using jQuery

Previously, I created a functionality for handling a single set of tabs. However, as the application has expanded, this functionality is no longer sufficient to accommodate multiple sets of tabs. The initial function looked like this: var iconTabs = func ...

Adjusting the size of MUI StaticDatePicker

Struggling to resize the MUI staticDatePicker component. It seems the only way is to adjust the sub-components individually, but I can't locate all of them. Here's what I've managed so far: <Field as={StaticDatePicker} id='bookin ...

Javascript enables the magnetization of cursor movements

Can a web page be designed so that when users open it and hover their mouse over a specific area outside of an image, the mouse is attracted to the image as if by a magnet? Is this idea feasible? Any suggestions would be appreciated. ...

How can I combine multiple values under the same key into a single dictionary or JSON format using Pandas and Python with Dataframes?

After examining the current dataframe: pd.DataFrame({'id':[1,1,1,2,2], 'key': ['a', 'a', 'b', 'a', 'b'], 'value': ['kkk', 'aaa', '5', 'kkk&ap ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Rearranging the Array based on the specific number in a consistent manner

I am in the process of developing a quiz creation platform. My goal is to display the answers to a question to users in a randomized order. My aim is to avoid the need to store the sequence in which the answers were presented by shuffling them randomly. ...