The .join() method isn't producing the expected result when trying to concatenate an array that is nested within an object inside

Currently, I am loading a file, extracting information from it, storing the data in an object, and then adding that object to an array. One of the attributes of the object is a 'sequence': [] key-value pair. After storing a DNA sequence in the 'sequence' value of my object, I am attempting to concatenate all the elements. However, my attempts to achieve this using .join() have been unsuccessful. Here is the code snippet I am working with:

// Checking for File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Success! All File APIs are supported.
} else {
  alert('The File APIs are not fully supported in this browser.');
}

var objArray = [];
var obj;

function parse(event) {
// Retrieving the file from an HTML input tag
var file = event.target.files[0];

if(file) {

    // Creating a new FileReader
    var reader = new FileReader();
    // When the reader loads
    reader.onload = function(evt) {
        // Storing the file contents in a variable
        var contentsByLine = evt.target.result.split('\n'); 
        // Notifying the user about the successful file upload
        console.log('File ' + file.name + ' was successfully loaded.');

        for(var i in contentsByLine){
            if(contentsByLine[i][0] == '>'){
                obj = {
                    id: contentsByLine[i],
                    sequence: [],
                    lead_trim: 0,
                    trail_trim: 0
                };
                objArray.push(obj);
            }else{
                obj.sequence.push(contentsByLine[i]);
            }
           // console.log(objArray[i]['sequence']);
        }
        console.log(objArray)

        // Creating a DataView.
        var dataView = new Slick.Data.DataView();

        // Using the DataView as a data provider for SlickGrid.
        var grid = new Slick.Grid("#table", dataView, columns, options);

        // Making the grid respond to DataView change events.
        dataView.onRowCountChanged.subscribe(function (e, args) {
          grid.updateRowCount();
          grid.render();
        });

        dataView.onRowsChanged.subscribe(function (e, args) {
          grid.invalidateRows(args.rows);
          grid.render();
        });

        var data = [];

        for (var i in objArray){
            objArray[i]['sequence'].join();
            data.push(objArray[i]);
        }

        dataView.setItems(data);
        dataView.getItems();
        //console.log(data);
    }
    reader.readAsText(file);
} else {
    alert('Failed to upload file!');
}

}

document.getElementById('fileItem').addEventListener('change', parse, false);

Answer №1

Your usage of the join method is incorrect. Remember that join returns a value, so you need to assign it to something.

for (var i in objArray){
    objArray[i]['sequence'].join();
    data.push(objArray[i]);
}

A correct way to write this would be:

for (var i = 0; i < objArray.length; i++){
    objArray[i]['sequenceString'] = objArray[i]['sequence'].join();
    data.push(objArray[i]);
}

Answer №2

One way to save the output is by assigning it to a variable like this:

let output = objArray[i]['sequence'].join();
storage.push(output);

A more concise version:

storage.push( objArray[i]['sequence'].join() );

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

Bring the element to the top of the page by clicking on the anchor within the element or anywhere within the specified div ID

I am looking to implement a functionality where the page scrolls to the top of the navigation div ID when a link inside the navigation div is clicked, or ideally even when clicking anywhere within the div itself that contains the navigation links. After r ...

"Reposition all elements contained within a div that have a specific class

I'm completely new to Javascript and I've been trying to move all elements with a specific class inside a particular div. After doing some research, I found a solution that worked using IDs. However, when I tried to adapt it to work with classNam ...

Displaying Kartik's growling animation using AJAX within Yii2 framework

Utilizing kartik growl to display a message via ajax success I attempted the following: This is the javascript code: $.post({ url: "forwardpr", // your controller action dataType: 'json', data: {keylist: keys,user:userdata}, success: f ...

Invalid extra parameters in the $.ajax function

I am attempting to access a web service in order to retrieve some data. I must include this URL using the GET method: http://localhost/ecosat/ws/api.php?t=vw_motorista However, when I check in Chrome Developer Tools, the link is shown as: http://localho ...

Typescript implementation for structuring JSON response data from API calls

As a beginner in Typescript, I am eager to create a straightforward weather application using Firebase functions. One of the initial steps involves making an API call to fetch the current temperature of a particular city. Upon making the API call, the JSO ...

Using jQuery AJAX to send data containing symbols

When making an AJAX call, I am including multiple values in the data like this: var postData = "aid="+aid+"&lid="+lid+"&token="+token+"&count="+count+"&license="+license; postData = postData + "&category="+category+"&event_name="+e ...

Unable to properly zoom in on an image within an iframe in Internet Explorer and Google Chrome

My image zoom functionality works perfectly on all browsers except for IE and Google Chrome when opened inside an iframe. Strangely, it still functions flawlessly in Firefox. How can I resolve this frustrating issue? The image link was sourced from the i ...

Bootstrap: Retrieve an image from a modal

I am working on a modal that contains a variety of selectable images. When an image is clicked, I want to change the text of the button in the modal to display the name of the selected image. Additionally, I would like to grab the selected image and displa ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...

Verification is required for additional elements within the div block once a single checkbox has been selected

Currently, I am working in PHP using the CodeIgniter framework. I have a question regarding implementing a functionality with checkboxes and validation using jQuery. Here is the scenario I want to achieve: There are four checkboxes, and when one checkbox ...

Trouble arises when adding HTML elements to a Content Editable Div. Any text inputted after programmatically inserting HTML content will merge with the last HTML tag instead

https://i.sstatic.net/bKIVm.pngI am currently working on a project that involves creating message templates within an app. Users have the ability to add placeholders for fields like names to these templates by clicking a button. They can also remove these ...

What is the best way to determine the quantity of utilized elements in an array of structures in the C programming language?

Imagine this scenario: struct a b[4]; //some elements of b have been filled I am trying to determine the count of non-empty elements in b. Given that I'm unsure if b contains exactly 4 non-empty elements, is there a method to achieve this? ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

Tips for accessing hidden field values in a second jsp page

I have a webpage called page1.jsp where I am including hidden fields. Here is the code snippet: <form action = "page2.jsp" method = "post" id = "hiddenValuesForm"> <input type = "hidden" name = "userData" value="" id = "useDataID"> <input t ...

Unexpected behavior in ReactJS when using Material UI

In my Webpack + ReactJS project, I am working on creating a table using Material UI. I am trying to implement an 'icon menu' feature with a 'menu item' that allows users to delete a specific line along with its associated data. Below i ...

Center a sans-serif font vertically with exact precision while adjusting the font size

My issue is an expansion of a previous problem I mentioned in another question, which can be found here Vertically align sans-serif font precisely using jquery/css. To summarize: I am aiming to align two divs containing text, with one positioned above the ...

By utilizing geocoordinates, arrange items in order of proximity to the individual's current location

Looking to organize an array based on the user's location in an AngularJS/ionic app. Specifically, the goal is to rank restaurants that are closest to the current user location 1/ Within my controller.js, I have the following code to retrieve the use ...

Determine the mean value from an array of JSON objects in an asynchronous manner

Can you help me calculate the average pressure for each device ID in this JSON data set? [ { "deviceId": 121, "Pressure": 120 }, { "deviceId": 121, "Pressure": 80 }, { "deviceId": 130, "P ...

Ways to create a variable in a function that can adapt without being tied to a variable that changes

Apologies for the vague title, but I am uncertain of the correct term for my issue. I am working on dynamically generating a table of clickable elements using for loops in JavaScript. Each element, when clicked, should execute the same function but with di ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...