When assessing a list against an array of objects in JavaScript

I am currently working on some Angular code with the objective of minimizing the use of Angular 1.x functionality, as it will be refactored in the near future.

My task involves comparing an array:

  let subscription = [
  "Cinemax Subscription", 
  "Disney Subscription", 
  "Encore Subscription", 
  "Epix Subscription", 
  "HBO Subscription", 
  "MLB Subscription", 
  "NBA Subscription", 
  "NHL Subscription", 
  "Division"
]

with an array of objects that have a key-value relationship containing another array:

let profiles = [
    {
        name:"1+ Adults in Household",
        qualifiers: [
            {
                name: 'Number of adults in the household'
            }
        ]
    },
    {
        name: '75k',
        qualifers: [
            {
                name: 'Division'
            },
            {
                name: 'Income'
            }
        ]
    },
    {
        name: 'Time Warner',
        qualifers: [
            {
                name: 'Division'
            }
        ]
    }
]

I am facing challenges with indexing and looping through these arrays.

let profilesFiltered = [];

Initially, I attempted to use a filter and Angular.forEach to compare the arrays.

let filteredProfiles = subscription.filter( function (src) {
    angular.forEach(profiles, function (key, index) {
        if(src === key.qualifiers[index].name) {
            profilesFiltered.push(key);
        }
    })
});

When inside the if statement, I noticed that:

key.qualifiers[index].name // 'Number of adults in the household'

initially matches:

subscription[0]   // but then moves on to 1 in the first object which is not there.

I can see where the issue is arising but I'm unsure how to properly loop through the qualifiers in the profiles array.

The desired outcome is to filter out those profiles that include Division as the last item in the array.

profilesFiltered = [
    {
    name: '75k',
    qualifers: [
      {
        name: 'Division'
      },
      {
        name: 'Income'
      }
    ]
  },
  {
      name: 'Time Warner',
      qualifers: [
          {
              name: 'Division'
          }
      ]
  }
]

Any insights or feedback would be greatly appreciated at this stage.

Thank you.

Answer №1

To narrow down the profiles, you can apply a filter by combining the filter() and some() methods:

profiles.filter(v => v.qualifiers.some(q => subscription.includes(q.name)));

let subscription = [
  "Cinemax Subscription",
  "Disney Subscription",
  "Encore Subscription",
  "Epix Subscription",
  "HBO Subscription",
  "MLB Subscription",
  "NBA Subscription",
  "NHL Subscription",
  "Division"
]

let profiles = [{
    name: "1+ Adults in Household",
    qualifiers: [{
      name: 'Number of adults in the household'
    }]
  },
  {
    name: '75k',
    qualifiers: [{
        name: 'Division'
      },
      {
        name: 'Income'
      }
    ]
  },
  {
    name: 'Time Warner',
    qualifiers: [{
      name: 'Division'
    }]
  }
]

let res = profiles.filter(v => v.qualifiers.some(q => subscription.includes(q.name)));


console.log(res)

Answer №2

Seeking something similar? Take a look at my code snippet below:

let profiles = [
    {
        name:"1+ Adults in Household",
        qualifiers: [
            {
                name: 'Number of adults in the household'
            }
        ]
    },
    {
      name: '75k',
      qualifiers: [
        {
          name: 'Division'
        },
        {
          name: 'Income'
        }
      ]
  },
  {
      name: 'Time Warner',
      qualifiers: [
          {
              name: 'Division'
          }
      ]
  }
];

let subscription = [
  "Cinemax Subscription", 
  "Disney Subscription", 
  "Encore Subscription", 
  "Epix Subscription", 
  "HBO Subscription", 
  "MLB Subscription", 
  "NBA Subscription", 
  "NHL Subscription", 
  "Division"
];

let profilesFiltered = profiles.filter(function (a) {
  // first filter all element in the profiles array 
  // check if their qualifiers array is not empty
  return a.qualifiers.some(function (b) {
    // filter the qualifiers array by checking the property name 
    // is it matching any element from subscription array
    return subscription.indexOf(b.name)!==-1;
  });
});

console.log(profilesFiltered);

Answer №3

Check out this code snippet that demonstrates how to work with data structures. It utilizes the reduce function for the operation. For handling duplicates, you can refer to this solution.

Explore the code on JS Bin: https://jsbin.com/dexagiresa/2/edit?js,output

let profiles = [
{
    name:"1+ Adults in Household",
    qualifiers: [
        {
            name: 'Number of adults in the household'
        }
    ]
},
{
    name: '75k',
    qualifiers: [
        {
            name: 'Division'
        },
        {
            name: 'Income'
        }
    ]
},
{
    name: 'Time Warner',
    qualifiers: [
        {
            name: 'Division'
        }
    ]
}
];



let subscription = [
  "Cinemax Subscription", 
  "Disney Subscription", 
  "Encore Subscription", 
  "Epix Subscription", 
  "HBO Subscription", 
  "MLB Subscription", 
  "NBA Subscription", 
  "NHL Subscription", 
  "Division"
];


var filteredProfiles = profiles.reduce(function (collectedResults, profile) {

    var newResults = profile.qualifiers.reduce(function(foundQualifiers, qualifier) {

        if(subscription.indexOf(qualifier.name) > -1) {
            return foundQualifiers.concat(qualifier.name);
        } else {
            return foundQualifiers;
        }

    }, []);

    return collectedResults.concat(newResults);

}, []);

document.write(filteredProfiles);

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 is the best way to retrieve an AJAX response in advance of sending it to a template when utilizing DATAT

Recently, I've been working on integrating log tables into my admin panel using the datatable plugin. Despite setting up an ajax call in my datatable, I'm facing issues with retrieving the response before sending it to the table. Here's a s ...

Ways to determine if the user is either closing the browser or navigating to a different website

I am looking to set up session management in a manner where all sessions are expired or destroyed when the user closes the browser or tab. However, I would like to retain all the sessions if the user is navigating to another website. Is there a way to ac ...

Error found in Paper.js at line 81: Uncaught TypeError - Unable to access properties of undefined (specifically '1') while utilizing Material UI and Joy UI

I am encountering an issue while using react js with material UI and JoyUI, where I am getting a blank screen. Below is the code snippet causing the problem: import React from 'react'; import { CssVarsProvider } from '@mui/joy/styles'; ...

What is the best way to use Jasmine to test a controller that relies on inputs from its dependencies?

Service UserService: (function() { 'use strict'; angular.module('kprModule',[]).service('UserService', UserService); function UserService() { function getUsername(){ return 'johnDoe&apos ...

Transform JSON String into Object using jQuery

Recently, I came across a JSON String in this format. {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} I needed to convert it into an object structure like this [{"label":"label","label1":"67041","label2":"745"," ...

What is the reason for create-react-app initializing twice?

After creating a react app using the command npx create-react-app, I encountered an issue: import React from 'react'; class Costly { constructor() { console.log('creating costly class'); } } function App() { const costlyRef ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

Ways to apply Angular ng-options outside of a select element besides traditional use?

According to the official documentation, ng-options can be used on any element, not limited to just the select tag. This flexibility allows for enhanced customization of the selection UI, such as displaying thumbnail images or additional information beyond ...

Convert the dynamic table and save it as a JSON file

Looking for the most effective method to save dynamic table data into JSON format. I have two tables that need to be saved into a single JSON file. While I can easily access and console log the regular table data, I'm having trouble retrieving the td ...

Ways to Fix the React Hydration Issue in Next.js

I have been encountering an issue with the error message "Hydration failed because the initial UI does not match what was rendered on the server." I am unsure of what is causing this error and would appreciate any insights or suggestions from others who ma ...

Microsoft Edge version 41.x is causing issues with cutting off AngularJs 1.x expression markup

Encountering a problem when using basic angular syntax in the Microsoft Edge browser. It appears that Edge cuts off lengthy angular expression markup unexpectedly. As an example: ng-disabled="conditionOne || conditionTwo || conditionThree" Gets shorten ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

Issues with AngularJS email validation specifically related to domain names are causing errors

Hello, I'm currently working on an AngularJS application where I'm implementing email validation. I'm facing an issue where I expect an error message to appear when I enter 'test@test', but it's not working as intended. Here ...

Deleting object property within Angular ng-repeat loop

I have information structured like this: $scope.cart={"4": {"cost": 802.85, "description": "test", "qty": 1}, "5": {"cost": 802.85, "description": "test", "qty": 1}}; My goal is to iterate through this data and show it with a remove button. How can I s ...

Is there a way to stop mUI from displaying the dropdown menu once Chrome automatically fills in a user's address details?

I am currently developing a form for users to enter their address in order to collect a billing address for payment information. Our services are only available to customers within the United States, so we have implemented an autocomplete UI component with ...

What is the best way to convert my MySQL data into JSON in a specific format?

I need help with outputting MySQL data into various formats below: timelist, usersex, and userage from the users table. <script type="text/javascript"> timeList = new Array(), userSex = new Array('female','male','male') ...

VueJS File Upload Field Failing to Reset Post Successful Submission

I am facing an issue in my VueJS application where the form does not clear all field values after submission, especially the file upload field. After a successful submission, the uploaded file name still remains displayed on the screen. Below is the code ...

The ng-click event is not triggering the Controller Function as expected

This is the Code for My View <div ng-controller="signupCtrl"> <ul class="list-group" > <li class="list-group-item"> <div class="form-group"> <input type="text" ng-model="signupCtrl.firstName"> ...

How can I implement jQuery Ajax to handle multiple elements on a single webpage?

I recently created a page where users can add items to their "favorites" list using the following JavaScript code: $(function(){ $('.doit-01234').click(function (e) { e.preventDefault(); $.ajax({ url: "https://www.domain. ...