Ways to determine if the keys of an object are present in an array, filtered by the array key

Working on an Angular 2 Ionic application and I'm wondering if there's a straightforward way to filter individuals by age in a specific array and then verify if any key in another object matches the name of a person in the array, returning a boolean value.

Here is an example array:

personsArr = [{
        "name": "Ram",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91e3f0fcd1f6fcf0f8fdbff2fefc">[email protected]</a>",
        "age": 23
    },
    {
        "name": "peter",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deadb6a7bfb3eced9eb9b3bfb7b2f0bdb1b3">[email protected]</a>",
        "age": 23
    },
    {
        "name": "John",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="610b0e090f21060c00080d4f020e0c">[email protected]</a>",
        "age": 33
    },
    {
        "name": "Bob",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55373a376667153238343c397b363a38">[email protected]</a>",
        "age": 41
    }
]

And here is an object:

personObj = {
    "peter": "helper",
    "Ram": "helper",
    "Bob": "helper"
}

I want to know how to filter personsArr by age and then check for any matching key from personObj with a person's name.

I think using a loop could work, but I'm open to suggestions if there's a better approach. Any help or advice would be greatly appreciated.

Answer №1

If you want to achieve this, use the filter method along with some. First, filter the array based on your condition and then check for matches on the object provided. I hope this explanation is useful.

const personsArr = [{
    "name": "Ram",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbfaca08daaa0aca4a1e3aea2a0">[email protected]</a>",
    "age": 23
    }, {
        "name": "peter",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f2c37263e326d6c1f38323e3633713c3032">[email protected]</a>",
        "age": 23
    }, {
        "name": "John",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22484d4a4c62454f434b4b4e0c414d4f">[email protected]</a>",
        "age": 33
    }, {
        "name": "Bob",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a5a8a5f4f587a0aaa6aeabe9a4a8aa">[email protected]</a>",
        "age": 41
    }];

const personObj = { "Ram": "helper", "Bob": "helper" };

const personObj2 = { "Ram2": "helper", "Bob2": "helper" };

const checkArr = (age, arr, obj) => arr.filter((f) => f.age > age).some((d) => obj[d.name]);

console.log('Expecting true');
console.log(checkArr(30, personsArr, personObj));
console.log('Expecting false');
console.log(checkArr(30, personsArr, personObj2));

Answer №2

Here is the code snippet:

// Filter by age
const minAge = 18 // example value
const validPerson = personsArr
    .filter(person => person.age > minAge)
    .some(person =>
        Object.keys(personObj).some(key => key === person.name)
    )

// Sort by age
personsArr.sort((a, b) => a.age > b.age ? 1 : -1)
const validPerson2 = personsArr.some(p =>
    Object.keys(personObj).some(pk => pk === p.name)
)

Answer №3

It seems like you're looking for a solution similar to the following:

const isMatch = peopleArray.some((element) => element.age > 30 && personObject.includes(element.name));

Make sure to adjust element.age > 30 with your specific filtering conditions.

Answer №4

Whether you choose to loop or not, looping is a necessary part of the process. One way to approach this is by utilizing the Array.filter method.

personsArr.filter((val) => val.age === age && Object.keys(roles).indexOf(val.name) > -1);

For a more comprehensive understanding, here is a full example:

const personsArr = [
    { "name": "Ram", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295b4844694e44484045074a4644">[email protected]</a>", "age": 23 },
    { "name": "peter", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47342f3e262a757407202a262e2b6924282a">[email protected]</a>", "age": 23 },
    { "name": "John", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1cbcec9cfe1c6ccc0c8cd8fc2cecc">[email protected]</a>", "age": 33 },
    { "name": "Bob", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ceee3eebfbeccebe1ede5e0a2efe3e1">[email protected]</a>", "age": 41 }
];

const personObj = { "peter": "helper", "Ram": "helper", "Bob": "helper" };

function filter(age: number, roles: { [name: string]: string }) {
    const keys = Object.keys(roles);
    return personsArr.filter((val) => val.age === age && keys.indexOf(val.name) > -1);
}

// 0: Object { name: "Ram", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b392a260b2c262a222765282426">[email protected]</a>", age: 23 }
​// 1: Object { name: "peter", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfacb7a6beb2edec9fb8b2beb6b3f1bcb0b2">[email protected]</a>", age: 23 }
console.log(filter(23, personObj));

// 0: Object { name: "Bob", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e1ece1b0b1c3e4eee2eaefade0ecee">[email protected]</a>", age: 41 }
console.log(filter(41, personObj));

Answer №5

var individualsArr = [    
{"name":"Sam", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d5f4c406d4a404c4441034e4240">[email protected]</a>", "age":23},    
{"name":"Sophia", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e2d36273f336c6d1e39333f3732703d3133">[email protected]</a>", "age":25},  
{"name":"Ethan", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e18b8e898fa1868c80888dcf828e8c">[email protected]</a>", "age":30},    
{"name":"Emma", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91f3fef3a2a3d1f6fcf0f8fdbff2fefc">[email protected]</a>", "age":41}   
];

var individualObj = {"Sophia":"assistant","Sam":"assistant", "Emma":"assistant"}

var newIndividualsArr = individualsArr.filter((individual) => individual.age<30);
var verify = false;
for(var key in individualObj) {
  newIndividualsArr.map((individual) => {
  if(individual.name === key){
   verify = true
  }
  });
}


console.log(verify);

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

User creation causing redirection malfunction

Recently, while working on a website, I encountered an issue with the registration process for users. It was functioning properly when I tested it a few days ago. After making some updates to other aspects of the website such as the login and profile sect ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

Eliminate the need to input the complete URL every time when making server calls

Currently, my springbok application has a React-Typescript frontend that is functioning well. I am using the request-promise library to make requests like this: get('http://localhost:8080/api/items/allItems', {json: true}). However, I would like ...

What is the method to retrieve content from a different domain using .load()?

When I try to retrieve data from a different domain using .load() or other jQuery ajax functions, it doesn't seem to work. However, accessing URLs on my own domain works perfectly fine. I've heard about a workaround involving PHP and setting up ...

Checking the validity of subdomain names using JavaScript/jQuery

For users signing up, my form allows them to choose a subdomain for their account. The valid characters allowed in the subdomain are letters, numbers, and dashes. Spaces and most special characters should be filtered out. http://_________.ourapp.com To r ...

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

The method for storing a user's choice in my array and subsequently selecting an element at random

Seeking assistance in developing a program that can play an audio list at various durations. The plan is to have the duration for elements 4 through 8 based on user selection, with the program playing each element within that range during the initial round ...

How to Validate Response/ Data value from PHP using Ajax

Currently, I am in the process of validating a sign-up form by utilizing ajax to call a php script that checks for existing email addresses. If the email address already exists in the database, an error message should be returned to the ajax function throu ...

JavaScript resets the timer whenever the page is refreshed

Is there a way to maintain the timer in a quiz even after refreshing the page? <html><h1>Js Timer</h1> <div style="font-weight: bold;" id="quiz-time-left"></div> <script type="text/javascript"> var total_seconds = ...

Is it not odd that there are two '=>' symbols in an arrow function when there is typically only one? What could this possibly signify?

function updateStateValue(name) { return (event) => { setState({ ...state, [name]: event.target.checked }); }; } To view the full code example, visit CodeSandbox. ...

Best practices for working with child components in Vue.js using TypeScript: Steer clear of directly mutating props

I feel like I'm stuck in a loop here. Currently, I have a Vue.js 2 app set up and running with TypeScript. However, I'm encountering an issue when trying to pass data to a child component that originates from the store. <template> < ...

How to efficiently deliver a document to a user using the MEAN stack

The express controller code snippet I'm working with involves creating a CSV file and sending it back to the user: // Correct file path and write data var currentDate = new Date(); var storagePath = path.join(__dirname,'../../public/reports/&apo ...

Outputting HTML with functions

I have a function that returns HTML code. renderSuggestion(suggestion) { const query = this.query; if (suggestion.name === "hotels") { const image = suggestion.item; return this.$createElement('div', image.title); } ...

Tips for streamlining code using switch statements in vue.js

Is there a more efficient way to simplify this switch statement for handling 5 different cases? Can I streamline the process of updating the completion status based on each step? data() { return { stepOneIsCompleted: false, ...

I encountered a permission error while trying to npm install, despite running the command with root privileges

After running npm install as root, I am still encountering permission errors. This is unfamiliar territory for me. I have attempted using chmod -R 777 *, and chown nobody:nogroup -R * within the project folder, but to no avail. Here's the specific er ...

What is the correct way to shut down a Node.js Express server?

Upon receiving a callback from the /auth/github/callback URL, I am faced with the task of closing the server. Utilizing the standard HTTP API, the server can be closed using the server.close([callback]) API function. However, when working with a node-expre ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

Shifting HTML table in Javascript by toggling checkboxes

When I click the checkbox, the table elements are not displaying inline. I am simply hiding the class "box". Do I need to write a special format? By default, the elements are displayed inline but when I check the checkbox, they shift. The column 'Stat ...

What is the best approach for managing client-side routes when a page refresh displays the backend Rails route instead?

After deploying my SPA to Render, I encountered an issue. My application comprises a React frontend with Redux and a Rails backend. When the app initializes, it correctly displays the frontend route in the browser. Subsequent navigation without refreshing ...

After creating a new Packery using AngularJS, the getElementById function may return null

Alright, so I've got this HTML markup: <button ng-click="create()">create list</button> Every time I click it, I create a new list using the Packery jQuery plugin. app.directive('packery', ['$compile', function($com ...