Issue with splitting an array and eliminating commas - angular/ReactJS

Console Error: Unhandled error during execution of mounted hook Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split')

It seems to work up until it comes across a group that has no data for continent.

This looks like the issue to me but I'm not sure how to solve it.

Also, I would appreciate a better solution to removing duplicates and trailing commas in all fields of the JSON. Is there a more efficient way to achieve this with just one function?

Any assistance is greatly welcomed

     JSON
      "response": [
{ 
"group": { 
"continent": "ASIA,EUROPE,ASIA,EUROPE,ASIA,ASIA,EUROPE,EUROPE,ASIA,AUSTRALASIA,AUSTRALASIA,EUROPE,",
"location": "AS,AS,AS,AS,EU,AF,EU,AF,AU,AU,AU,AU,", 
}, 
},
{ 
"group": {
"continent": "ASIA,EUROPE,AFRICA,EUROPE,ASIA,AFRICA,EUROPE,",
"location": "AS,AS,AS,AU,AU,", 
}, 
},
{ 
"group": {
"continent": "ASIA,",
}, 
},
{ 
"group": {
"continent": "EUROPE,",
}, 
},
{ 
"group": {
"continent": "ASIA,EUROPE,",
"location": "AU,AU,"
}, 
},
 ....
]
 
methods: {
 removeDuplicates() {
      const  uniques = [];
      this.response.group.continent.split(",").forEach((l) => {
        if ( uniques.indexOf(l) == -1 && l !== "") {
           uniques.push(l);
        }
      });
      console.log(" uniques : " +  uniques);
      this.continent =  uniques.join(", ");
    },
}

mounted() {    
    this.removeDuplicates();
  }

Answer №1

Uncaught TypeError: Cannot read property 'split' of undefined

The error occurs because the value of this.response.group.continent is not defined

To fix this, try accessing the data using this.response[0].group.continent instead

Answer №2

Upon encountering the error message, it appears that this.response.group is not a string. Further examination of your data reveals that this.response consists of an array of objects. To remedy this situation, you will need to iterate through the array in order to access the group property of each object. Employing Array.forEach with slight adjustments should help rectify the issue:

const uniques = [];
this.response.forEach(({ group }) => {
  group.continent.split(",").forEach((l) => {
    if (uniques.indexOf(l) == -1 && l !== "") {
        uniques.push(l);
    }
  });
});

Below is a functioning example (not a VueJS app, but demonstrates the same logic as proof-of-concept):

const response = [{
    "group": {
      "continent": "ASIA,EUROPE,ASIA,EUROPE,ASIA,ASIA,EUROPE,EUROPE,ASIA,AUSTRALASIA,AUSTRALASIA,EUROPE,",
      "location": "AS,AS,AS,AS,EU,AF,EU,AF,AU,AU,AU,AU,",
    },
  },
  {
    "group": {
      "continent": "ASIA,EUROPE,AFRICA,EUROPE,ASIA,AFRICA,EUROPE,",
      "location": "AS,AS,AS,AU,AU,",
    },
  },
  {
    "group": {
      "continent": "ASIA,",
    },
  },
  {
    "group": {
      "continent": "EUROPE,",
    },
  },
  {
    "group": {
      "continent": "ASIA,EUROPE,",
      "location": "AU,AU,"
    },
  },
];

const uniques = [];
response.forEach(({ group }) => {
  group.continent.split(",").forEach((l) => {
    if (uniques.indexOf(l) == -1 && l !== "") {
      uniques.push(l);
    }
  });
});

console.log("Uniques: " + uniques);
const continent = uniques.join(", ");
console.log(continent);

Even better: utilize Set() + Array.prototype.flatMap()

An enhanced approach involves leveraging ES6 features such as Set(), which maintains a list of unique entries. Utilizing Array.prototype.flatMap + Array.prototype.filter (to eliminate empty entries) simplifies passing the flattened array of continents into the set:

const continents = response.flatMap(({ group }) => group.continent.split(',')).filter(v => !!v);
const uniques = Array.from(new Set(continents));

Refer to the example below:

const response = [{
    "group": {
      "continent": "ASIA,EUROPE,ASIA,EUROPE,ASIA,ASIA,EUROPE,EUROPE,ASIA,AUSTRALASIA,AUSTRALASIA,EUROPE,",
      "location": "AS,AS,AS,AS,EU,AF,EU,AF,AU,AU,AU,AU,",
    },
  },
  {
    "group": {
      "continent": "ASIA,EUROPE,AFRICA,EUROPE,ASIA,AFRICA,EUROPE,",
      "location": "AS,AS,AS,AU,AU,",
    },
  },
  {
    "group": {
      "continent": "ASIA,",
    },
  },
  {
    "group": {
      "continent": "EUROPE,",
    },
  },
  {
    "group": {
      "continent": "ASIA,EUROPE,",
      "location": "AU,AU,"
    },
  },
];

const continents = response.flatMap(({ group }) => group.continent.split(',')).filter(v => !!v);
const uniques = Array.from(new Set(continents));

console.log("Uniques: " + uniques);
const continent = uniques.join(", ");
console.log(continent);

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

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Guide to assigning unique identifiers to all elements within an array using JavaScript

I have an array of objects with numeric keys that correspond to specific data values. I am attempting to restructure this object in a way that includes an 'id' field for each entry. Here is the original object: [ { "1": "data1", "5": "d ...

What is the best way to prevent automatic trimming in EJS variable assignment in Node.js?

When I attempt to write a variable from the database into an EJS table, it is being displayed with default trimming by the EJS template. However, I would like to display the variable from the database without any default trimming. I consulted the EJS temp ...

Utilizing dual identifiers in a Jquery plugin

I am currently working with a jQuery plugin and I need to apply the same functionality to two different IDs. How can I achieve this? It involves a next and previous functionality where clicking on the next button automatically scrolls both divs. The issu ...

What steps can be taken to enhance cleanliness and efficiency, and what are some recommended practices to adhere to?

Currently, I am in the process of developing a user authentication system on the backend. Specifically, I have implemented a POST method for registering new users. userRouter.post("/", expressAsyncHandler(async (req, res) => { try { const { na ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

AngularJS - Swipe to update

I've been trying to use the pull to refresh plugin for Angular JS, but unfortunately it's not working for me. Even though I can see the text, when I try to pull nothing happens! I followed all the steps outlined on this GitHub page: https://githu ...

Deploy a Vue.js application using Docker containerization technique

I am looking to dockerize my VueJS application. While I can successfully install and run my application on localhost using npm install and npm run serve commands on my local machine. To containerize the application, I have created a Dockerfile as follows: ...

The process of registering with JWT tokens and the challenge that arises when a token expires

I had the idea to implement a registration process that requires users to provide their username, email (which must not already exist in the database), password, and confirm password. The project is built using NextJS with pages router and Typescript. impo ...

Nuxt dynamically passes props through the router

Currently using Nuxt Experiencing difficulties with transferring data between pages Seeking to programmatically navigate to another page and pass a JavaScript object This is the code I have written so far: In my component where the navigation occurs: t ...

Error: an empty value cannot be treated as an object in this context when evaluating the "businesses" property

An error is occurring stating: "TypeError: null is not an object (evaluating 'son['businesses']')". The issue arose when I added ['businesses'][1]['name'] to 'son' variable. Initially, there was no error wi ...

What is the best way to retrieve the "name" and "ObjectId" properties from this array of objects? (Using Mongoose and MongoDB)

When trying to access the name property, I encountered an issue where it returned undefined: Category.find() .select("-_id") .select("-__v") .then((categories) => { let creator = req.userId; console.log(categories.name) //unde ...

Displaying ISO date format within a date input field using React

Currently, I am working on a project where I am editing records retrieved through an API. Within the data, there are two fields that represent dates. The format of the date data from the API is in "2021-07-30T20:34:40.545Z", whereas the input field display ...

Retrieving a JSON element using its name within a subquery in a Node.js MySQL environment

I've been working on a project that involves NodeJS and Mysql for the backend. Everything was going smoothly until I encountered a small issue after adding a SUBQUERY. Below is the Mysql Query: var GetHistoryPayments = function(code){ var qu ...

Extract the content of a textbox within an iframe located in the parent window

Is it possible to retrieve the value of a text box in an iframe from the parent page upon clicking a button? Below is an example code snippet showcasing the situation: <div> <iframe src="test.html" > <input type=text id="parent_text"> & ...

The function is not recognized in C# programming language

Whenever I try to trigger functions by clicking buttons, nothing seems to happen and an error message appears in the console. Uncaught ReferenceError: AddressInputSet is not defined at HTMLButtonElement.onclick I'm new to this and could use ...

Update the background URL of a div element using an HTML tag

My question is about a CSS div with set dimensions and background that I want to change on hover. I am aware that this seems like a simple task, but what I really want to do is retrieve the background sources from within the HTML tag itself. For example: ...

Testing multiple regex patterns using jQuery

I am attempting to run multiple regex tests on an input field. Here is the script: $("#search-registration").keyup(function () { var input_data = $('#search-registration').val(); var regexTest = function() { this.withPrefix = /^ ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

Run code once the Firestore get method has completed its execution

Is it possible to execute code after the get method is finished in JavaScript, similar to how it can be done in Java (Android)? Below is an example of my code: mColRef.get().then(function(querySnapshot){ querySnapshot.forEach(function(doc) { ...