Encountering issues with reading the length property error within the jsonstore function in the MobileFirst

Hello, I'm a newcomer to the world of Javascript and MobileFirst. I am currently attempting to retrieve and display a list of JSON values:

[{"_id":1,"json":{"age":10,"name":"carlos"}},{"_id":2,"json":{"age":10,"name":"carlos"}}]

However, when trying to output these values in the DOM, it fails and shows this error message:

03-27 04:29:19.035: E/NONE(3093): Uncaught Exception: Uncaught SyntaxError: Unexpected token o at (compiled_code):311

Below is the function causing the issue:

main.js:

 function add(){
    var collectionName = 'people';

    // Object that defines all the collections.
    var collections = {

      // Object that defines the 'people' collection.
      people : {

        // Object that defines the Search Fields for the 'people' collection.
        searchFields : {name: 'string', age: 'integer'}
      }
    };

    // Optional options object.
    var options = {


    };

    WL.JSONStore.init(collections, options)

    .then(function () {

      // Data to add, which could be obtained from a network call.
      var data = [{name: 'carlos', age: 10}];

      // Optional options for add.
      var addOptions = {

        // Mark data as dirty (true = yes, false = no), default true.
        markDirty: true
      };

      // Get an accessor to the people collection and add data.
      return WL.JSONStore.get(collectionName).add(data, addOptions);
    })

    .then(function (numberOfDocumentsAdded) {
      alert("Data successfully added.");
    })

    .fail(function (errorObject) {
        alert("Data failed to be added.");

    });

}
function display(){
var collectionName = 'people';



var options = {
 };

WL.JSONStore.get(collectionName)

.findAll()

.then(function (arrayResults) {

    var arrayResult = '{"files":' + arrayResults + '}';
    alert(arrayResults.length);
    var jsonData = JSON.parse(arrayResult);
    alert (jsonData.files.length);
    alert(jsonData);



     var full_list = "";
    for (var i = 0; i < jsonData.files.length; i++) {
        var file = jsonData.files[i];
        full_list =  full_list + file.json.name + " " + file._id + " is " + file.json.age + '<br />';
        $("#demo").append(full_list); 


    }



})
.fail(function (errorObject) {
});


 }

index.html

<a href="#" onclick="display();" >click here to display the data</a>
        <br /> 
        <a href="#" onclick="deldocument();" >click here to delete the data</a>
        <p id="demo"></p> <br /> 
        <a href="#" onclick="destroy();" >click here to destroy the data</a>
        <p id="demo"></p> <br />

I would greatly appreciate any assistance with this issue. Thank you all so much.

Answer №1

When you attempt to JSON.parse an object, it may throw the error "Unexpected token o" because it is trying to parse obj_to_parse.toString(), resulting in [object Object]. To resolve this, try using JSON.parse('[object Object]').

Here is the output:

//arrayResults = [{_id: 1, json: {name: 'carlos', age: 99}}]

Consider reading it in the following manner:

var full_list="";
for(var i=0;i<arrayResults.length;i++){ 
    // alert(arrayResults[i]._id);
    // alert(arrayResults[i].json.name); 
    // alert(arrayResults[i].json.age);
   full_list =  full_list + arrayResults[i].json.name + " " + arrayResults[i]._id + " is " + arrayResults[i].json.age + '<br />';
$("#demo").append(full_list);  
}

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

Activate Vuetify to toggle a data object in an array list when the mouse hovers over

I'm currently working on a project where I need to toggle a Vuetify badge element for each item in an array when the containing div is hovered over. While I've been able to achieve a similar effect using CSS in a v-for loop with an array list, I ...

"Dynamic Addition of Textboxes to Webpages with the Help of jQuery

Currently, I am facing a challenge in adding a textbox to a webpage in ASP.NET MVC using jQuery. My goal is to have a button that, when clicked, appends a text box to the existing collection of Textboxes with a specified class. Below is the jQuery code sni ...

The code begins executing even before the function has finished its execution

I believe that is what's happening, but I'm not entirely sure. There's code in a .js file that invokes a function from another .js file. This function performs an ajax call to a php page which generates and returns a list of radio buttons wi ...

Is it possible to utilize "this" in mapMutations spread within Vue instance methods?

Trying to define Vuex mutations like this: export default { props: { store: String }, methods: { ...mapMutations({ changeModel: `${this.store}/changeModel` }) } } Encountering an error message: An er ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

Converting a nested JsonObject into a formatted string representation

I need to convert the 'points' value into a string. Currently, it is in Object form. { "note": "testing", "Area": "India", "workId": "21390", "points ...

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

Having trouble resolving the dependency injection for stripe-angular

Attempting to integrate the stripe-angular module into my Ionic/AngularJS application. https://github.com/gtramontina/stripe-angular I have installed the module using npm install stripe-angular. This is how I include the dependency in my app: var myApp ...

JavaScript code snippet to remove a specific element from an array and store it in an object

I am looking to convert an array into an object, where each item in the array is separated into categories as shown below. let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal'] I expect the output to b ...

troubleshooting problems with jquery ajax and setInterval

$(document).ready(function() { function refreshBids() { var element = $("#biddingDiv"); element.load("bids.php?id=<?=$userId;?>&init=1&auctionid=<?=$auctionId;?>"+(new Date()).getTime()); } refreshBids(); setI ...

Is there a way to prevent form submission when validation fails in an AJAX callback?

I am currently working on submitting a form with validation using ajax. After the ajax response, if the input field is valid, the form should submit; otherwise, an error message should be displayed. Below is the HTML code: <form action="new-join.php" m ...

Fixed columns with horizontal scrolling to prevent Datatables columns from overlapping

I'm facing an issue with my data table created using datatables. I need to fix the first two columns, but when I do so, the other two columns overlap them while scrolling horizontally. If I remove the fixed columns, the scrolling works correctly witho ...

Issue with GTM: The use of this language feature is restricted to ECMASCRIPT_2015 mode or higher: constant declaration

I'm having trouble extracting UTMs and transferring them to specific fields through my script, but it seems like the script isn't functioning properly on GTM. (Interestingly, the script does work when directly added to webflow custom code) var ...

Failure to Acknowledge Asynchronous Behavior in Loop

I've hit a roadblock with an Async function. My Objective - I'm building a batchProcessing function (batchGetSubs) that will iterate through a set of files, extract an ID, make an API request, wait for a response (THE ISSUE), and then write the ...

Identify the moment when the SPAN element reappears in sight

I have a question that may have been asked before, but I haven't found a satisfactory answer yet. Within my HTML code, I have a SPAN element with an onclick event, like so: <span onclick='loadDiv()'>Text</span> When a user cli ...

Unique ActionBar design for my NativeScript-Vue application

I'm currently working on customizing the ActionBar for my nativescript-vue app. I have implemented FlexBoxLayout within the ActionBar, but I am facing an issue where the icon and title of the bar are not aligning to the left as intended; instead, they ...

Code snippet in webpage body

Hey there, I could really use some assistance: I currently have the following: A) Login.html B) Documentation.html C) Base.html Within the login page, there is a form with fields for User and Password. In Documentation, there are links to various folder ...

Can anyone explain why the Splice function is removing the element at index 1 instead of index 0 as I specified?

selectedItems= [5,47] if(this.selectedItems.length > 1) { this.selectedItems= this.selectedItems.splice(0,1); } I am attempting to remove the element at index 0 which is 5 but unexpectedly it deletes the element at index ...

AngularJS - ng-change does not trigger for checkbox that toggles the class "switch"

CSS Styling: <span style="color: blue;">Hello, World!</span> JavaScript Function: function showMessage(){ alert('Hello!'); } I tried to implement a span element with blue text color. However, the function that was supposed to ...

Maximizing the Potential of Return Values in JavaScript

I have a JavaScript code that retrieves information and displays it in a div. It's functioning properly, but I want to dynamically change the div id based on the returned data. For example: function autoSubmit3() { $.post( 'updatetyp ...