Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data.

data: MyModel[] = [
{
  id: 1,
  name: 'Name',
  secondName: 'SecondName'
}

In addition, I have created the interface MyModel:

interface MyModel {
id: number,
name: string,
secondName: string

Suppose that I have received data from the Back-End in the form of a JSON object:

{
id: 2,
FIRSTname: 'FName',
secondName: 'SecondName'
}

How do I validate whether the keys in the object match my interface?

For instance, if the field "FIRSTname" is incorrect, then I need to handle it by throwing an exception or other method.

Answer №1

Perhaps there could be an alternative approach in typescript, in es6 you have the option to:

const data = [
  {
    id: 2,
    name: 'FName',
    secondName: 'SecondName'
  },
  {
    name: 'foo',
    secondName: 'bar'
  },
];
const validate = ({id, name, secondName}) => id && name && secondName

const validData = data.filter(validate)
console.log(validData);

Keep in mind that if any of the values: id, name, secondName, are null, the validate function will return false.

Answer №2

Imagine a scenario where you define a variable called obj that implements the model interface. You then proceed to initialize all its properties and compare those keys with another set of data from the backend, which we'll refer to as respDataObj.

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { //To check values in nested arrays
            if (!this[i].compare(testArr[i])) return false;
        }
        else if (this[i] !== testArr[i]) return false;
    }
    return true;
}
Object.keys(respDataObj).compare(Object.keys(obj))

This comparison function is credited to:

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

Finding the right property by comparing it with an array of objects in a MongoDB aggregation query

In my mongoDB collection, I have a field called 'abc' that contains an array of objects structured like this: 'abc': [{"_id": new ObjectId("someId"), "name": "entity name"}] I am looking to perfo ...

What steps can be taken to stop 'type-hacking'?

Imagine owning a popular social media platform and wanting to integrate an iframe for user signups through third-party sites, similar to Facebook's 'like this' iframes. However, you are concerned about the security risks associated with ifra ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

Stop users from being able to copy text on their smartphones' internet browsers

I am currently working on creating a competitive typing speed challenge using JavaScript. Participants are required to type all the words they see from a div into a textarea. In order to prevent cheating, such as copying the words directly from the div, o ...

What is the title of the commonly used state management approach in rxjs? Are there any constraints associated with it?

When working with Angular applications, it is common to use the following approach to manage shared states: import { BehaviorSubject } from 'rxjs'; interface User { id: number; } class UserService { private _users$ = new BehaviorSubject([]) ...

script to pause video using jQuery

I have a script that works perfectly, but currently it only stops an instance of a playing video if a new video is started. I want to modify the script so that ALL instances of playing videos are stopped when the function stopAllButMe(); is called. Can s ...

Upon refreshing the page, nested React routes may fail to display

When I navigate to the main routes and their nested routes, everything works fine. However, I encounter an issue specifically with the nested routes like /register. When I try to refresh the page, it comes up blank with no errors in the console. The main r ...

Problem with Ext.net TabPanel

I am encountering a problem with the Ext.net TabPanel. Every time the page containing the tab panel is opened for the first time after the application has been rebuilt, it throws an error Uncaught TypeError: Object [object Object] has no method 'getCo ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...

Iterate through the call feature repeatedly, ensuring that each call has a different iteration number assigned to a variable within the

I have a situation where I need to call a certain feature (which has validations) multiple times within a loop. Currently, my code successfully calls the feature 3 times. * def xxx = """ function(times){ for(i=0;i<times ...

Utilizing Node.js to retrieve streams in conjunction with OpenAI

I am currently working on setting up a node/react setup to stream results from openai. I came across an example project that accomplishes this using next.js. While I have successfully made the API call and received the results as expected, the challenge li ...

Create a new chart using completely unique information

I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modif ...

Utilize shell scripting on Linux to parse JSON data

Similar Question: Parsing JSON using Sed and Awk I have an example of a JSON string provided below. I am interested in extracting the value of the "uptime" field to use as a variable in a shell script. How can I achieve this? { "serverStatus" : { " ...

React modal not triggered on click event

As a newcomer to react, I am exploring a modal component import React, { useState, useEffect } from 'react'; import { Modal, Button } from "react-bootstrap"; function TaskModal(props) { return ( <Modal show={pro ...

Using Kotlin on the Android platform, learn how to convert a string into a JSON string

Seeking to convert a string into a JSON string using Gson. My desired outcome is to transform "email" into "{"email" : "$email"}" I have the function: fun serializeUserEmail(email: String): String { return &quo ...

The `ngx-infinite-scroll` feature does not function properly on mobile devices when used in conjunction with the

I'm currently working on an Angular project that utilizes the mat-sidenav layout and routing. I came across an issue when trying to display a list of elements from a database using ngx-infinite-scroll. Following the user guide for ngx-infinite-scroll, ...

React-Collapsible Compilation Error

Currently, I am working on a project that involves Spring and ReactJS. I am still new to front-end development. One of the tasks I am trying to accomplish is creating a simple accordion using "REACT-COLLAPSIBLE". The code I have written is quite straight ...

The response from AngularJS $resource can be considered as both an array and an object

Recently, I obtained this JSON file: [ { "name": "paprika", "imgSrc": "img/paprika.jpg" }, { "name": "kurkku", "imgSrc": "img/kurkku.jpg" }, { "name": "porkkana", "imgSrc": "img/porkkana.jpg" }, { "name": "lehtisalaatti", " ...

Creating a Music Bingo game to ring in the New Year

Looking to create a Music Bingo game for New Year's Eve with randomized songs that can be selected, but experiencing an issue where nothing happens when you have 4 in a row. Attempted adding a submit button, but it doesn't trigger any action. Ide ...