Determine the presence of either one or both values in a JavaScript object

I was looking at an Object like this:

{"user": {
    "name": "Harry Peter",
    "phoneNumber": "12345",
    "products": [
        {
            "type": "card",
            "accountId": "5299367",
       },
        {
            "type": "Loan",
            "accountId": "5299365", 
        },
        {
            "type": "card",
            "accountId": "8299388", 
        },
     ]}
}

My question is whether the user has both a loan and a card product, or just a loan.

Are there any existing functions in JavaScript or Angular that can help me find out?

If anyone has suggestions on how to accomplish this, please share. Thank you!

Answer №1

If you're looking to determine whether a user has both a loan and a card, or just a loan as their product, the filter array method could be useful.

var obj = {
    "user": {
    "name": "Harry Peter",
    "phoneNumber": "12345",
    "products": [
        {
            "type": "card",
            "accountId": "5299367",
       },
        {
            "type": "Loan",
            "accountId": "5299365", 
        },
        {
            "type": "card",
            "accountId": "8299388", 
        },
     ]
  }
};
      
var loans = obj.user.products.filter(function(product){
      return product.type === "Loan";
});
      
console.log("Loans: " + loans.length);

if(loans.length === obj.user.products.length){
    console.log("The user has only loans");
}else{
    var cards = obj.user.products.length - loans.length;
    console.log("The user has "+loans.length+" Loan(s) and "+ cards+ " Card(s).");
}
      

If you want more information on how this method works, feel free to check out this link.

My goal is to determine if the user possesses both a loan and a card, or simply a loan within their product list.

By utilizing the filter method in conjunction with comparing the length of the loans array to the length of all products, you'll be able to address your query effectively.

Answer №2

You can iterate through the elements in products to extract distinct types

var records = {
  "user": {
    "name": "Harry Peter",
    "phoneNumber": "12345",
    "products": [{
      "type": "card",
      "accountId": "5299367",
    }, {
      "type": "Loan",
      "accountId": "5299365",
    }, {
      "type": "card",
      "accountId": "8299388",
    }, ]
  }
}
                 
var uniqueTypes= records.user.products.reduce(function(previous, current){
  if(previous.indexOf(current.type)<0) previous.push(current.type)
  return previous;                
}, [])
    
console.log(uniqueTypes)

Answer №3

Feel free to experiment with the following code snippet:

var obj = {
  "user": {
    "name": "Harry Peter",
    "phoneNumber": "12345",
    "products": [{
      "type": "card",
      "accountId": "5299367",
    }, {
      "type": "Loan",
      "accountId": "5299365",
    }, {
      "type": "card",
      "accountId": "8299388",
    }, ]
  }
};

var results = {};

obj.user.products.reduce(function(prevVal, item) {
  prevVal[item.type] = true;
  return prevVal;
}, results);

console.log(results.card && results.Loan); // returns true
// It is worth mentioning that 'results' contains all unique values for types and can be utilized accordingly

Answer №4

This specific approach offers a Same Iteration solution that accurately determines whether the type is distinct from Loan.

var obj = {"user": {
    "name": "Harry Peter",
    "phoneNumber": "12345",
    "products": [
        {
            "type": "card",
            "accountId": "5299367",
       },
        {
            "type": "Loan",
            "accountId": "5299365", 
        },
        {
            "type": "card",
            "accountId": "8299388", 
        },
     ]}
};
      
function haveDifferentProducts(products){
    var isDiff = false;
    products.forEach(function(product){
       isDiff = product.type != "Loan"; //checks if type not loan
    });
    return isDiff;
}
console.log(haveDifferentProducts(obj.user.products))

Answer №5

Utilize the Array filter() method for efficient data filtering.

See it in action with this working demo:

var jsonObj = {
  "user": {
    "name": "Harry Peter",
    "phoneNumber": "12345",
    "products": [
      {
        "type": "card",
        "accountId": "5299367",
      },
      {
        "type": "Loan",
        "accountId": "5299365", 
      },
      {
        "type": "card",
        "accountId": "8299388", 
      },
    ]   
  }
};

var totalLoan = jsonObj.user.products.filter(function(item){
      return item.type == "Loan";
});


var totalCards = jsonObj.user.products.filter(function(item){
      return item.type == "card";
});

if(totalCards.length < 1 && totalLoan.length < 0) {
  console.log("Only loan");
} else if (totalCards.length > 0 && totalLoan.length < 1) {
  console.log("Only card");
} else {
  console.log("Both card as well as loan");
}

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

When the window is fully loaded, JavaScript executes

Can someone help me set up this script to start running when the page loads? I want the vat field to automatically show up if the company name has been entered. Thank you! //--></script> <script type="text/javascript>//-- $('.colorbox ...

Confidential data in Module Design

I'm curious about the concept of private variables in JavaScript. How is it that I can still access a private variable through a public method and redefine the properties of the module? For example: var aModule = (function() { var privateVar = 1 ...

Issue with setting HTML content using jQuery's .html() method

I have a simple functionality. When a user clicks on the edit link, it transforms the previous element into an input element for editing, and changes the edit link into a cancel link. If the user decides not to edit, they can click on cancel and everything ...

Using Vuejs to implement pagination on a weekly basis

I need some help with Vue pagination. I have a ticket object, and currently, it displays in a certain way. What I'm trying to achieve is to display the tickets weekly. For example, if this week is the 31st week of the year, then from today until Sunda ...

Connecting AngularJS controllers and services through data binding

I'm having trouble with setting up data binding between my controller and service. The issue seems to be with calling the factory method from other services and seeing the controller attributes update accordingly. I've tried different approaches ...

Slow loading time when switching between items in the drop-down menu from the Main Menu

Visiting my website at europebathroom.com, you will notice a horizontal main menu with dropdown functionality. When hovering over a menu item, the corresponding dropdown appears seamlessly. Yet, sometimes quickly touching another menu item unintentionally ...

Update a nested object key by concatenating key names with "." to create a string

Imagine having this specific object structure: var obj = { level1 :{ level2: { level3: { title: "champion" } } } } Now the goal is to update the title key using a provided string (note that it's a string, not an actua ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

Enable my textbox to interpret the html img tag

Is there a way to display emoji images instead of emoji symbols when inserting them into my textbox? For example, can I show the image representation of ':)' instead of just the symbol itself? ...

How to prevent collapse when selecting a node in React.js Mui Treeview

Is there a way to prevent the Treeview from collapsing every time a node is selected? I want it to render a button based on the selected node. Here's an example that I've created: https://codesandbox.io/s/summer-water-33fe7?file=/src/App.js ...

Error: 'POST Request Processing Failure: Content-Type Missing'

My front end Canvas is transformed into a png file that needs to be POSTed to a third party vendor's API. The response comes back to Node as a base64 file which I decode, but upon attempting the upload, an error occurs: Error processing POST reques ...

Acquiring the root URL with the $location service in AngularJS

I am facing a situation where I have a specific URL structure like the one shown below. http://localhost:8080/test#/users/list Upon further investigation, I discovered the following information: $location.url() returns -> "users/list" $location.path( ...

Guide for animating individual mapped elements in react-native?

After mapping an object array to create tag elements with details, I added an animation for the tags to zoom in on render. However, I wanted to take it further and animate each tag individually, sequentially one after the other. This appears to be a common ...

Utilizing a Web Interface for Remote Monitoring of Windows Servers

I am in need of creating a webpage that will indicate whether a server is currently operational or not. These servers are all Windows based, with some running on 2008 and others on 2003. They are spread across different networks within various client locat ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

In Nodejs, there is a way to determine the size of a document stored

I have a question: How can I determine the size of a cursor, in terms of kilobytes (KB), without actually fetching it? I've come across various sources, such as this post on Stack Overflow, but I don't want to retrieve the query result just to f ...

Creating a mandatory 'Select' component in Material UI with React JS

Is there a method to show an error message in red until a choice is selected? ...

Is there a way to input text instead of a URL into the Smmry API?

I have a very specific question that I'm not sure anyone can answer, but I'll ask anyway. The Reddit TLDR bot uses the Smmry API to summarize content, and I'm trying to create something similar. However, the documentation only mentions passi ...

React Native's state changes dynamically, however, the JSX conditional rendering fails to update the user interface accordingly

Greetings and thank you in advance for your time! I'm currently facing a unique challenge with React where I am struggling to render a specific UI element based on a check function. My goal is to create a multiple selection filter menu, where clickin ...

What is the best way to get rid of a tooltip from a disabled button

I am facing an issue with my button that is disabled using ng-disabled. The problem is that the button still shows a tooltip even when it is disabled. I need to find a way to remove the tooltip when the button is disabled. Check out my Button ...