What is the best way to confirm if a specific input is included in a JSON array?

This data belongs to me

Each time a user inputs a code, it must be unique. If the value already exists, an error message should be displayed indicating that the branch code already exists.

 branches: [
          {
            code: "test",
            name: "test",
            email: "test",
            website: "test.com",
            phone: "test",
            address: {
              street: "test",
              city: "test",
              township: "test",
              state: "test",
              zip_code: "test",
              country: "test",
            },
            google_maps_url: "test.com",
          },
        ],

Here is my code. Do not focus on company_details at the moment as I have not provided all the data. This is a more complex situation where I am unable to display errors for specific index fields. The index is passed as a parameter to the function in v-on blur.

 for(var i=0; i < this.company_details.branches.length; i++){
        if( this.company_details.branches[i].code == this.company_details.branches[index].code){
          count +=1;
        }

        if (count==2){
          this.BranchCodeArray[index].exists = true;
        }
        else{
          this.BranchCodeArray[index].exists = false;
        }

Answer №1

To my understanding, you are looking to check if a certain input exists in the code field within the given data.

Utilizing the filter method can help determine the number of items that match the input. If the resulting array's length is greater than 0, then the input is not unique.

const branches= [
  {
    code: 'test',
    name: 'test',
    email: 'test',
    website: 'test.com',
    phone: 'test',
    address: {
      street: 'test',
      city: 'test',
      township: 'test',
      state: 'test',
      zip_code: 'test',
      country: 'test'
    },
    google_maps_url: 'test.com'
  }
];

const doesExist = 'code';
const doesNotExist = 'does not exist'

const exists = !!branches.filter((branch) => branch.code === doesExist).length

const notExists = !!branches.filter((branch) => branch.code === doesNotExist).length

An alternative approach could be mapping over the data to create a flat array of codes. By doing so, you can easily check if the codes array includes the input data provided.

const branches= [
  {
    code: 'test',
    name: 'test',
    email: 'test',
    website: 'test.com',
    phone: 'test',
    address: {
      street: 'test',
      city: 'test',
      township: 'test',
      state: 'test',
      zip_code: 'test',
      country: 'test'
    },
    google_maps_url: 'test.com'
  }
];

const doesExist = 'code';
const doesNotExist = 'does not exist'

const codes = branches.map((branch) => branch.code);

if(codes.includes(doesExist)){
  // Your error logic
}

codes.includes(doesNotExist)

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

Facilitate parent directory navigation

Hello everyone! I am currently developing an express application. At the top of my express file, I added this line to serve all static files from my working directory: app.use(express.static(__dirname)); Now, I am trying to send a file that is located in ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

The error message thrown is: "Unable to assign headers after they have already been sent to the client."

I've been attempting to make a GET request, but it keeps failing at the app.js res.json line. app.js app.use(function(err, req, res, next) { res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; ...

`Cannot recompile the `Product` model as it has already been compiled. Please try again

I attempted to reference my productSchema within my purchaseSchema but encountered the following error: OverwriteModelError: Cannot overwrite Product model once compiled. What steps can I take to resolve this issue? Here is my product schema: mongoose = ...

Creating a banner using four grid elements, with each element containing four child elements, is a simple process that can

Can you assist me in recreating my idea from an image? I am having trouble understanding how to select and place other elements, and then return them to their original positions after deselecting... I attempted to use a grid but it did not work properly. ...

Tips for getting JavaScript to identify a context_dict object from views.py in Django

Recently, I inherited a Django project from a former colleague and now I need to make some changes to the code in order to add a new line to a Google Viz line chart. As the line chart already exists, my approach is to closely follow the logic used by my p ...

Enable Class exclusively on upward scrolling on the browser

Is there a way to dynamically change the class of an element only when the user scrolls the browser page upwards? Issue Filide>> JavaScript $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll <= 100) { ...

What steps should I take to resolve npm start issues within my Node.js application?

Upon completing the npm install, I attempted to run npm start for my project. Unfortunately, an error was displayed. What steps can be taken to resolve this issue?view image of the error here ...

What is the process for making an ajax call in CakePHP?

It may seem obvious, but I've searched the internet and couldn't find any useful or updated information on this topic. I'm attempting to make an ajax request in CakePHP controller to retrieve both view contents and JavaScript code. The aja ...

Incorporate pug and sass into your React project for a more

Are pug/jade and sass compatible with react? I enjoy organizing my code by separating files, and the functionality that sass and pug provide is great for this purpose. Is there a way to integrate pug and sass into a react project? Pug example: doctype ...

Error message: Laravel unable to locate requested page

Attempting to make a post request using AngularJS in Laravel, I encountered the following error message: Oops! The page you are trying to access could not be found. JAVASCRIPT app.controller('main',['$scope','$http',&apos ...

Concerns about the Dependency Tree in React

I need some assistance with my current issue. I'm having trouble installing the mui search bar component. npm i --save material-ui-search-bar Unfortunately, I'm encountering this error message: PS Z:\WebDev\ApplyWithin\frontend> ...

You cannot utilize Lesson as a JSX Component in Next JS TypeScript

Below is my updated page.tsx code: import Aspects from '@/components/Aspects'; import FreeForm from '@/components/FreeForm'; import Lesson from '@/components/Lesson'; import React from 'react'; import { Route, Route ...

What is the best way to process the bytes from xhr.responseText?

Is there a way to successfully download a large 400+ mb Json file using xmlhttprequest without encountering the dreaded Ah Snap message in Chrome due to its immense size? One potential solution I've considered is implementing setInterval() to read th ...

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

Three pie or doughnut charts instead of one are utilized within Chart.js

Can multiple charts be nested inside one another? To see an example of a single chart and what I would like - where the first one is placed inside the second one and so on - please refer to this js fiddle. var data = [ { label: "title 1", value: ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

What is the best way to include a JavaScript function in a dynamically generated div?

By clicking a button, I am able to dynamically generate a table row that contains a div element with the class "contents." $(document).on("click", ".vote", function() { // Removing selected row var rowLoc = this.parentNode.parentNode. ...

Alter the displayed content of the component based on the tab that is selected

How can I change the content of a div outside of v-tabs based on the selected tab? I want to use the tabs as a navigation bar and not contain the content within the tabs. Do I need to use v-router within the component and give each tab a different href? M ...

The DOM fails to reflect changes in the data variable in VueJS

I am facing an issue while trying to update an array of arrays and display it as a reactive variable, however the DOM does not seem to reflect those changes. To achieve this, I have two components - a parent component and a child component: Parent Compon ...