JavaScript - Insert a new key and value into an Object

Within my function, I have a forEach loop to create an Object:
Please execute the code snippet:

angular.module('myApp', []).controller('myCntl', function($scope) {
  $scope.t = '';
   var input = "a,b,c,d,e,r \n1,1,1,1,1,1\n2,2,2,2,2,1 \n3,3,3,3,3,1";
  var rows = input.split('\n');
  var result = {
    header: [],
    body: []
  };

  //Extract Header

  var headerString = rows[0].split(',');
  headerString.forEach(function(val) {
    result.header.push(val);
  });

  rows.splice(0, 1);
  rows.splice(rows.length - 1, rows.length); 

  // Extract Body 'a,b,c,d,...'
  rows.forEach(function(val, i) {
  
    var bodyString = val.split(',');
    var objBody = new Object;

    bodyString.forEach(function(val, i) {

      var strHeader = result.header[i];
      objBody[strHeader] = val;
    });

    result.body.push(objBody);
  });

  $scope.result = result.body;

  $scope.show = function() {
    console.log($scope.result)
    $scope.t = $scope.result;
  }



});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" ng-app="myApp" ng-controller="myCntl">
  <button ng-click="show()">click me</button>
  <span ng-repeat="item in t">
   {{item}}
  </span>
</div>

This is the objBody after the forEach loop:

objBody = {   
    a: "1",  
    b: "1",  
    "c": "1"  
}

My concern lies with the key enclosed in double quotes in the last record of objBody.
What does it signify? and Why?! > ("c")

https://i.sstatic.net/Dcy0I.png

Answer №1

The issue arose because of the presence of white space between r and \n in the input string. Upon splitting the string by \n, rows[0] would be "a,b,c,d,e,r ". Subsequently, when split by comma, the last element will retain the white space as seen in "r ".

To resolve this problem:

var input = "a,b,c,d,e,r \n1,1,1,1,1,1\n2,2,2,2,2,1 \n3,3,3,3,3,1";

change it to:

var input = "a,b,c,d,e,r\n1,1,1,1,1,1\n2,2,2,2,2,1\n3,3,3,3,3,1";

This adjustment addresses the issue.

angular.module('myApp', []).controller('myCntl', function($scope) {
  $scope.t = '';
   var input = "a,b,c,d,e,r \n1,1,1,1,1,1 \n2,2,2,2,2,1 \n3,3,3,3,3,1";
  input = input.replace(" ","");
  console.log(input);
  var rows = input.split('\n');
  var result = {
    header: [],
    body: []
  };

  //Get Header

  var headerString = rows[0].split(',');
  headerString.forEach(function(val) {
    result.header.push(val);
  });

  rows.splice(0, 1);
  rows.splice(rows.length - 1, rows.length); //delete "" row, from end array

  // Get Body 'a,b,c,d,...'
  rows.forEach(function(val, i) {
    var bodyString = val.split(',');
    var objBody = new Object;

    bodyString.forEach(function(val, i) {

      var strHeader = result.header[i];
      objBody[strHeader] = val;
    });

    result.body.push(objBody);
  });

  $scope.result = result.body;

  $scope.show = function() {
    console.log($scope.result)
    $scope.t = $scope.result;
  }



});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" ng-app="myApp" ng-controller="myCntl">
  <button ng-click="show()">click me</button>
  <span ng-repeat="item in t">
   {{item}}
  </span>
</div>

EDIT: You may have come across some solutions. However, my recommended approach for removing white spaces from the dynamic input string is:

input = input.replace(" ","");

Answer №2

One of the solutions I found was using regular expressions to split the string:

var myRegex = new RegExp(/\s*\n/);
var rows = input.split(myRegex);

This code successfully splits every instance of ' \n' in the string, which worked perfectly for my situation.

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

Page refreshing in Angular 5 consistently redirects to the home page instead of staying on the current page

I am experiencing an issue with the navigation on my application. When I navigate to routes like getEmp-by-id or page-not-found and hit refresh, the application automatically redirects me back to app-home. However, I would like it to stay on the same pag ...

Shuffle math calculations involving subtraction by a percentage using node.js or JavaScript

Hello there! If you want to subtract, say 35%, from a number, you can use methods like this: var valueInString = "2383"; var num = parseFloat(valueInString); var val = num - (num * .35); console.log(val); But have you ever wondered how you could randomiz ...

What distinctions are there between saving a constant value in a variable and in state?

There are a couple of different approaches to accomplishing the same thing within a React functional component. When you have a config value that is only needed inside the component (just a constant value, never passed in or modified), you can either use a ...

Can you explain how HTML and JavaScript work together in terms of execution order?

As a newcomer to JavaScript, I'm curious about the execution order of line1, line2, and line3 in my code. My initial assumption was that it would display the paragraph first (line 1), followed by the image (line 2), and then trigger a prompt. However ...

What causes the toggle effect in my jQuery onclick function to alternate between on and off when the initialization is repeated multiple times?

I am facing an issue with my website where icons/buttons trigger a menu when clicked. I need to load more data by adding more buttons, so I tried re-initializing the existing buttons using a jQuery onclick function whenever the number of buttons changes. ...

Utilizing Bootstrap and JavaScript/JQuery for enhancing functionality in Android applications

I created a website that functions well on Google Chrome and other popular browsers. Now, I am looking to publish it for Android using PhoneGap for conversion. A challenge I encountered was that PhoneGap no longer supports Bootstrap or JQuery. Could you pl ...

How to display a modal within a router-link in Vue 3?

Below are buttons with router-links. However, I only want the calculator button to open a modal. When I execute the code provided, all buttons trigger the modal instead of just the calculator button. Output: https://i.sstatic.net/layQ1.png Router-link C ...

Transferring files from the android_asset directory to the SD Card

I am trying to play video files that are packaged within a Cordova application. My goal is to transfer these files from the android_asset folder to the SD card using the File API in JavaScript. However, I am encountering difficulties in accessing this fol ...

Step-by-step guide on generating a downloadable file in Vue

As a beginner in Vue, I am tasked with downloading a file but unsure of how to proceed. My attempt at the code resulted in the image opening on a new page instead. <a class = "btn btn-success btn-xs" href = "https://78.media.tumblr.com/tumb ...

increase the variable based on the count of clicks

I need some assistance with the code snippet below: Javascript: var counter = 0; var totalItems = 8; var remainingItems = $num - totalItems; if (remainingItems == 22) { $('#next').click(function(e) { e.preventDefault(); cou ...

Seeking to duplicate script for a new table without making any changes to the original script

I am working with two tables that require the capability to dynamically add and delete rows using separate scripts. How can I modify the second script so that it only affects the second table and not the first one? Table: <table id="myTable" class=" t ...

Retrieving a data value using a specific key within a JavaScript object

Trying to retrieve a specific value by providing the literal key in a JavaScript object. The image below indicates that "filter" is equal to "Approved", sourced from reimb_status_description. Line 6 of code assigns filter to the value. const filter = Obj ...

Is it possible for jquery JSON AJAX to block all users?

On my website, I use AJAX to load an RSS feed on the client side when the page loads. If a user repeatedly presses F5, could the owner of the RSS feed ban my entire website instead of just that one user? This would prevent others from loading the RSS feed ...

Is there a way to evenly space out sprites on a spherical surface in THREE.js?

I'm working on a fascinating project where I want to create a visually appealing database of words. The idea is to arrange the words in a sphere, with the most important ones closer to the top and less important ones further away. To achieve this, I m ...

Connecting ExtJS grid with Asp.net Websrvice: A step-by-step guide

I have exhausted all my efforts in attempting to retrieve the JSON data from my webservice. Despite being able to view the JSON data in Fiddler, I am facing an issue where the data is not binding with the grid. Below is the code snippet that I have been wo ...

What is the best way to activate useEffects in React before the rendering process occurs?

One challenge I'm facing is passing a prop from a parent component to a child component that dynamically changes based on user input. I am looking for a way to trigger a data fetch in the child component as soon as that prop changes, even before the ...

Activating events with Jquery

Can anyone help me with this HTML and jQuery issue I'm facing? When I click on an image for the first time (when it has the class 'hide'), the first jQuery click function is executed. However, when I click on the image again, the second func ...

Modifying npm packages within a web application

I have a web application where I recently installed an npm package. However, I've realized that I need to customize it by adding some code. My attempt to modify the package directly in node_modules hasn't resulted in any visible changes. Is there ...

Animating SVGs in Internet Explorer (IE)

I'm currently working on an animation project using SVG images and JS, but unfortunately, I've run into a roadblock with SVG animations not functioning correctly in Internet Explorer. Do you happen to know of any solutions that could make it work ...

What is the process for programmatically injecting a search query to activate the places_changed event for the Google Maps API?

Currently, I am working on a search page that includes a location input field. My goal is to automatically populate this input with a query if a user reaches the page from another source with a search query. Additionally, I want to trigger a place change e ...