Sorting through numerous arrays of objects with various properties

Currently, I am attempting to develop a filter function that will return data matching the specified value from a given set of string keys.

Here is an example of an array:

let data = [
 { id:1 , data:{ name:"sample1",address:{ cat:"business" } } },
 { id:2 , data:{ name:"sample2",address:{ cat:"office"  }  } },
 { id:3 , data:{ name:"sample3",address:{ cat:"office"  } } },
 { id:4 , data:{ name:"sample4",address:{ cat:"office"  }  } }
 { id:5 , data:{ name:"sample5",address:{ cat:"home"  } } }
 { id:6 , data:{ name:"sample6",address:{ cat:"home"  }  } }
]



function createFilter( collection , value ,key ){
  //insert code here 
}


let result = createFilter( data , "business" , [ "data","address","cat" ] )

console.log(result)

The expected output is:

{ id:1 , data:{ name:"sample1",address:{ cat:"business" } } },

Answer №1

Utilize the filter method for data searching and employ reduce to create the keys.

Keep in mind that filter will produce an array of matched items. If you desire only the first match, consider using find

const information = [
  { id: 1, data: { name: "sample1", address:{ cat: "business" } } },
  { id: 2, data: { name: "sample2", address:{ cat: "office" } } },
  { id: 3, data: { name: "sample3", address:{ cat: "office" } } },
  { id: 4, data: { name: "sample4", address:{ cat: "office" } } },
  { id: 5, data: { name: "sample5", address:{ cat: "home" } } },
  { id: 6, data: { name: "sample6", address:{ cat: "home" } } }
]

const searchMethod = (collection, keys, value) => 
  collection.filter(obj => keys.reduce((current, val) => current[val] || {}, obj) === value)
const outcome = searchMethod(information, ["data", "address", "cat"], "business")

console.log(outcome)

Answer №2

function customFilter( collection , value ,key ){
  const getNestedValue = (nestedObject, propertyPath) => {
      return propertyPath.reduce((obj, key) =>
          (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObject);

  };
  return collection.filter( item => getNestedValue(item, key) === value);
}

This custom filter function will find and return matching object(s) from the collection array or an empty array if there is no match.

let filteredResult = customFilter( myData , "business" , [ "myData","location","type" ] );

console.log(filteredResult); // [{"id":1,"myData":{"name":"sample1","location":{"type":"business"}}}]

let filteredResult2 = customFilter( myData , "office" , [ "myData","location","type" ] );

console.log(filteredResult2); //[{"id":2,"myData":{"name":"sample2","location":{"type":"office"}}},{"id":3,"myData":{"name":"sample3","location":{"type":"office"}}},{"id":4,"myData":{"name":"sample4","location":{"type":"office"}}}]

let filteredResult3 = customFilter( myData , "vacation" , [ "myData","location","type" ] );

console.log(filteredResult3); // [] 

Answer №3

Feel free to give this code a try.

If the solution provided does not fully address your issue or if you require additional functionality, please let me know. I am more than willing to update my answer accordingly.

function customFilter( items , searchTerm ,property ){
     for(var item of items) {
           if(item[property[0]][property[1]][property[2]] == searchTerm)
           { 
               return item;
           }
     }
     return null;
}

Answer №4

Utilizing Underscore and ES6 arrow syntax for clean code.

const isEqualTo = expected => actual => expected === actual;

function filterByDeepValue(collection, value, path) {
    const condition = _.compose(isEqualTo(value), _.property(path));
    return _.filter(collection, condition);
}

const data = [
    {id: 1, data: {name: "sample1", address: {cat: "business"}}},
    {id: 2, data: {name: "sample2", address: {cat: "office"}}},
    {id: 3, data: {name: "sample3", address: {cat: "office"}}},
    {id: 4, data: {name: "sample4", address: {cat: "office"}}},
    {id: 5, data: {name: "sample5", address: {cat: "home"}}},
    {id: 6, data: {name: "sample6", address: {cat: "home"}}},
];

console.log(filterByDeepValue(data, 'business', ['data', 'address', 'cat']));
<script src="https://underscorejs.org/underscore-umd-min.js"></script>

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

Tips for including products in the watchlist using ReactJS?

I am currently exploring ways to add items to a watchlist. The process I am attempting involves adding items to the watchlist page/component that I have developed when a user clicks on the add button. It is important to understand the hierarchy of the co ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

In this JavaScript tool for counting characters, every carriage return is counted as two characters

Hello there! I have created a character counter in JavaScript that looks like this: <textarea class="SmsText" id="txttemplate" maxlength="160" /> <span id="charsCount">160</span></strong><span>character(s) left</span> ...

"Concurrency issues arise when using multiple AJAX calls in jQuery, causing confusion with

This piece of JavaScript code involves a series of AJAX calls to my FastCGI module in order to retrieve certain values. However, there seems to be an issue where the value intended for display in "div2" is ending up in "div1", and vice versa, ultimately ca ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...

Displaying data on the user interface in Angular by populating it with information from the form inputs

I am working on a project where I need to display data on the screen based on user input received via radio buttons, and apply specific conditions. Additionally, I require assistance in retrieving the id of an object when the name attribute is chosen from ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...

Validating the value of a Material UI TextField

I am currently working with a TextField that has some validation requirements: minValue = 1 maxValue = 10 These validations are effective when using the arrows in the TextField, however, if I directly type into it, I am able to enter any number. How can ...

Child element casting shadow over parent element

I am currently using box shadow for both the parent (.map) and child (.toggle-button): .map { position: fixed; top: 20px; right: 0; width: 280px; height: 280px; z-index: 9999; box-shadow: 0px 1px 6px 0px rgba(0,0,0,0.3); } .map ...

Assistance with jQuery in Javascript is needed

Currently, I am in search of an effective vertical text scroller. My desired scroller would move vertically in a continuous manner, ensuring there is never any empty space while waiting for the next text to appear. I am open to using either JavaScript or ...

What is the process for inserting text or letters into a checkbox using Material Ui?

I am looking to create circular check boxes with text inside them similar to the image provided. Any help or guidance on achieving this would be greatly appreciated. View the image here ...

Prevent users from deleting options in Autocomplete by disabling the backspace key

I am currently working on implementing the Autocomplete component from Material-Ui library to allow users to select multiple options, but I want to restrict them from directly removing any of those options. One issue I've encountered is that users ca ...

Tips for showcasing Markdown files within subdirectories in Next.JS

In my Next.JS project, I am managing numerous Markdown files that are organized into various category folders. For example, I have folders named 'CategoryOne' and 'CategoryTwo' located at the root level of the project alongside node_mod ...

Placing elements from an array into a customized output

Currently, I am dealing with a unique output: dAmn_Raw('send chat:Sandbox\n\nmsg main\n\nthismessage'); In my code, there exists a variable: myvariable that stores a random value selected from an array I formulated. The cha ...

Having trouble deciphering the undefined jquery scroll at the top

I have been attempting to resolve this error without success, so I am turning to you with my specific issue. I am using a jQuery scroll feature that navigates to the hashtags in the menu. When it reaches the targeted hashtags, the menu item color should ch ...

The React component fails to render on the screen

Upon retrieving data from the database server, attempts to render it result in the data being shown in the console log but not displayed in the component. What could be causing this issue? useEffect(() => { readRequest().then(setTodos); c ...

``There seems to be an issue with the functionality of JSON.stringify

Upon attempting to use the JSON.stringify() method to convert an array of strings into a JSON object for passing to a PHP script, I encountered an issue where the method did not return any meaningful output. The code provided is the only one handling the ...

Vue.js: Iterating over objects using v-for causes keys to be displayed in unexpected order

I've encountered an issue where Vue is not honoring the sequence of keys. The initial data I provide to the Vue component as a prop appears as follows: [ { id: 1, event_name: "event 1", scheduled_at: "2021-01-01" }, { id: 2, ev ...

Creating a progress bar in CGI using Perl

Currently, everything is functioning correctly. However, the issue arises when trying to initiate the progress bar while sending emails. I have encountered difficulties implementing various examples of progress bars in CGI. The documentation available do ...

Apexchart abandons the wrapper upon adding dual Y-Axes

When attempting to add two Y-Axes to an Apexchart, it seems to extend beyond the wrapper and fails to resize correctly. My goal is to display one Y-Axis on the left side of the chart and another on the right. I attempted to troubleshoot using my dev tool ...