JavaScript array filtering causing errors and crashing

Currently, I'm developing a mobile application with NativeScript using Typescript/JavaScript. The code below is executed after completing a Bluetooth scan in the app. The main task is to identify the correct service from the available options. Unfortunately, when attempting to select the desired service, an issue arises at the line services.filter(function (obj) {. Despite looking through the error log, I can't seem to make sense of it...

console.log("Connect Variable");
var services: Array<string>;
var service: any;
services = []; //initialize array
bluetooth.connect(
    {
     UUID: _peripheral.UUID,
        onConnected: function (peripheral) {
            console.log("------- Peripheral connected: " + JSON.stringify(peripheral));
            peripheral.services.forEach(function (value) {
                console.log("---- ###### adding service: " + value.UUID);
                services.push(value);
            });

            service = peripheral.services.filter(function (obj) {
                return obj.UUID == 'A000';
            });
        },
    }
);

Here's the output from the console log:

CONSOLE LOG file:///app/Pages/Home/home.component.js:145:32: ---- ###### adding service: A000
CONSOLE LOG file:///app/Pages/Home/home.component.js:145:32: ---- ###### adding service: 180A
***** Fatal JavaScript exception - application has been terminated. *****
Native stack trace:
1   0xbea99 NativeScript::FFICallback<NativeScript::ObjCMethodCallback>::ffiClosureCallback(ffi_cif*, void*, void**, void*)
2   0x4ae381 ffi_closure_inner_SYSV
3   0x4b20b8 ffi_closure_SYSV
...
30  0x9e943 NativeScript::GlobalObject::moduleLoaderEvaluate(JSC::JSGlobalObject*, JSC::ExecState*, JSC::JSValue, JSC::JSValue)
31  0x44c4f9 JSC::ModuleLoaderObject::evaluate(JSC::ExecState*, JSC::JSValue, JSC::JSValue)
JavaScript stack trace:
1   onConnected@file:///app/Pages/Home/home.component.js:157:55
2   ...
3   UIApplicationMain@[native code]
4   start@file:///app/tns_modules/application/application.js:233:26
5   @file:///app/tns_modules/nativescript-angular/application.js:65:26

<p>Any ideas on what may be causing this error?</p>

<h1>Update:</h1>

<p>After taking Vladimir's advice, here’s the revised code:</p>

<pre><code>for (let i = 0; i < peripheral.service.count; i++) {
   if (peripheral.services.objectAtIndex(i).UUID == 'A000') {
      service = peripheral.services.objectAtIndex(i);
      console.log("selected service: ");
   }
}

However, despite this update, the following error persists:

JavaScript error: file:///app/Pages/Home/home.component.js:98:56: JS ERROR TypeError: undefined is not an object (evaluating 'peripheral.service.count')

Answer №1

It appears that the data structure in question is an NSArray rather than a JavaScript array, which is why the filter() method cannot be used. One potential solution is to iterate through the native NSArray and selectively copy the necessary objects, or alternatively, copy all objects and then apply a filter later on. For instance, you can follow this example to copy all objects:

let items = [];
for (let j = 0; j < collection.items.length; j++) {
   items.push(collection.items.objectAtIndex(j));
}

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

Storing JSON data using Vuex

As I am delving into the world of Vuex store used with vue.js, I find myself wanting to implement it in a specific scenario. 1. Is STATE referring to any data, whether static or dynamic, that is provided by the server or stored in a JSON format? TEMPLATE ...

Examining Input Information in React with Jest

I have developed a basic form using React and I am utilizing Jest for practicing unit testing. While testing my Form Component, which renders input values to the DOM, I keep encountering a TypeError: Cannot read property 'firstName' of undefined. ...

How can I dynamically change a key in an object and replace it with a custom name while also updating its value?

Transform this =>>>>> {1: "Baroque", 2: "Glitch Pop ", 3: "Nu Jazz", 4: "Drumfunk", 5: "Bitpop", 6: "Latin Pop", 7: "Carnatic"} into this ==>>>> [{id: 1 name ...

Passing a class object from a child component to a parent component in Angular 4

Passing a class object like Person from parent component to a child component is no issue. However, I would also like to manipulate this object in the child component and send it back to the parent component. The child component class looks like this: ex ...

React Typescript form input values not functioning properly

I'm exploring React for the first time and working on a multi-step contact form. I've created a handleChange function to retrieve the input value, so that when I navigate back and forth, the input content is displayed allowing for edits. The firs ...

Incorporate a Web Worker into your webpack library for enhanced performance

I am facing an issue while attempting to include a web worker in my custom npm package. [App] -> [my npm package -> load worker] Within the npm package, I am utilizing worker-loader to import the worker file: import Worker from 'worker-loader! ...

Tips on integrating JavaScript with embedded Ruby code

I am attempting to generate a flash message that displays after a user clicks a link in my js.erb file. $('a').click(function(){ <% flash.now[:alert]= "Successfully added "%> this.innerHTML <% "to cart" %> }) M ...

Click setting disables button's default behavior

Looking for a solution with my form setup: <form> <RaisedButton label={'next'} onClick={this.handleNext} type={'submit'} style={{marginRight: 12}}/> </form> I've noticed that ...

Could someone assist me in identifying the error or mistake?

For my project, I have implemented client and server sign-in & sign-up functionalities. However, after fetching the register API from the frontend, it is displaying an error message "please fill all fields" even though I have provided validation for al ...

Firebase Database: Unidentified node kind with separate Firebase initialization process

In order to replicate this issue, a minimal repository can be found at: https://github.com/ljrahn/firebase-unknown-node-type The problem arises when the firebase initialization logic is separated into a distinct package and then imported. This leads to an ...

Automatically refresh template string values without the need to reload the page

Whenever the page is refreshed, the template string gets automatically updated with a new value sourced from the database, constantly changing. Is there a method to incorporate ajax or a similar tool for refreshing the template string value automatically? ...

Switch up the color scheme of specific bars within the same dataset at regular intervals using Chartjs

Does anyone know how to change the color of two bars every five bars in a bar chart using Chart.js? I'm looking for something like: Red Red Blue Blue Blue Blue Blue Red Red Blue... This is the code I currently have: var chart = new Chart(ctx, { ...

The error message states: "TypeError: a.map is not a function"

I recently deployed my React JS app on Heroku and encountered some issues with the routing. While everything worked smoothly on my local host, I faced errors after fixing the routing problem that I couldn't resolve. Despite extensive research, I haven ...

Encountering difficulties importing an NPM library into StackBlitz

Hey there, I'm currently attempting to replicate an Angular example online but am encountering issues importing my Tabulator Library in stackblitz. I keep receiving an error when trying to import it in the hello component. import Tabulator from &apo ...

Elasticsearch error: elasticsearch reference not caught

Currently, I am in the process of developing a NodeJS application that utilizes Elasticsearch. Below is the code snippet: <!DOCTYPE html> <script src="../bower_components/elasticsearch/elasticsearch.js"></script> <script> function ...

Ajax TabContainer mysteriously vanishes during Postback

I'm currently working on a GIS web application using C# ASP.net. Within my project, I have an Ajax TabContainer that houses multiple TabPanels containing various elements like a map window and scale bar from the ESRI WebAdf toolkit. Below is a simpl ...

How to replace the xth occurrence with jQuery or JavaScript

Looking for a solution to update a specific character in a string like the following scenario: var str = "A A A A A"; The goal is to replace a particular 'A' with another value. For example, replacing the 3rd 'A' with some ...

achieve precise outcomes using mapping techniques

I am currently learning react.js and encountering an issue with obtaining specific results on the map. Below is the code I am working with: render(){ const friends = [ {id:1, name: 'Dave',age:50}, {id:2,name: 'Kellie',age:42}, {id:3, ...

Using an ASP button in combination with a JavaScript popup

Is there a way to add a confirmation dialog when clicking an asp:button that only triggers postback if the user clicks "OK"? Here's what I have so far: OnClientClick="if(confirm('Format the hard disk?')) alert('something'); else a ...

Encapsulate ng-style within quotation marks

I am trying to hide a span if the value of filters[*index*] is empty. var span = "<span ng-style='{ 'display': filters[" + filterIndex + "] == '' ? 'none' : 'inline-block' }'></span>" cell.html ...