Using JavaScript to split an array for organization

I'm looking to arrange my arrays by using the split function and then go through multiple items in those arrays.

Here's an example of an array structure:

var arr = [
{
"name": "bob",
"date": "1-1-2018",
"statistic": [
      "some title: 92nd (source, 2014)",
      "another title: 2.56 (source, 2014)",
      "title: 52.8% women (source, 2007/08)",
      "some title: 21.9% (source, 2016)",
      "another title: 3rd (source, 2016)"
    ]
},
{
"name": "sally",
"date": "1-1-2020",
"statistic": [
      "title: 8th (source, 2014)",
      "some title: 92nd (source, 2014)",
      "another: 40.8% women (source, 2007/08)",
      "some title: 21.9% (source, 2016)",
      "another title: 3 children (source, 2016)",
      "some title: 23rd (source, 2016)"
      "title: 46% (source, 2016)"
    ]
},
{
"name": "chris",
"date": "1-1-2021",
"statistic": [
      "some title: 46th (source, 2014)",
      "another title: 92nd (source, 2014)",
      "title: 52.8% women/children (source, 2007/08)"
    ]
},
//etc...
]

This is what I have attempted so far:

 for (let i=0; i < arr.length; i++) {
    for (let x=0; x < arr[i].statistic.length; x++) {
      arr[i].custom = {};
      arr[i].custom["statistics"] = [];
    var s = arr[i].statistic[x].split("(");
    console.log(unit);
    var l = s[0].split(":");
    var u = l[1].split(" ");

    arr[i].custom["statistics"].push({
      number: u[1],
      suffix: u[0],
      label: l[0],
      source: s[1]

    });
  }
}

How can I format my code like this?

var arr = [
{
"name": "bob",
"date": "1-1-2018",
"statistic": [
      "some title: 92nd (source, 2014)",
      "another title: 2.56 (source, 2014)",
      "title: 52.8% women (source, 2007/08)",
      "some title: 21.9% (source, 2016)",
      "another title: 3rd (source, 2016)"
    ],
"custom": {
      "statistics": [
{
    "number": "92nd",
    "suffix": "",
    "label": "some title",
    "source": "source, 2014)"
  },
  {
    "number": "2.56",
    "suffix": "",
    "label": "another title",
    "source": "CIA, 2017)"
  },
  {
    "number": "52.8%",
    "suffix": "women",
    "label": "title",
    "source": "source, 2007/08)"
  },
  {
    "number": "21.9%",
    "suffix": "",
    "label": "some title",
    "source": "source, 2016)"
  },
  {
    "number": "3rd",
    "suffix": "",
    "label": "another title",
    "source": "source, 2016)"
  }
],
etc...
}
},

]

The issue is that "arr[i].statistic[x]" returns undefined even though there are values in the array. I will address the parenthesis problem later on to make it "source": "(source, 2014)"

Thank you for your help!

Answer №1

Instead of iterating the outer array twice, make sure to iterate through each item's statistic in the inner loop. Consider using

for (let i=0; i < arr.length; i++) {
  arr[i].custom = {};
  arr[i].custom["statistics"] = [];
  for (let x=0; x < arr[i].statistic.length; x++) {
// … add more code here …

as your looping mechanism.

Furthermore, I noticed that you are logging a variable unit which hasn't been defined. Perhaps you meant to log s instead?

Answer №2

Ensure to carefully nest your loops and iterate over the correct items in order to avoid recreating arrays unnecessarily, resulting in only accessing the last item each time.

var arr = [{
    "name": "bob",
    "date": "1-1-2018",
    "statistic": [
      "some title: 92nd (source, 2014)",
      "another title: 2.56 (source, 2014)",
      "title: 52.8% women (source, 2007/08)",
      "some title: 21.9% (source, 2016)",
      "another title: 3rd (source, 2016)"
    ]
  },
  {
    "name": "sally",
    "date": "1-1-2020",
    "statistic": [
      "title: 8th (source, 2014)",
      "some title: 92nd (source, 2014)",
      "another: 40.8% women (source, 2007/08)",
      "some title: 21.9% (source, 2016)",
      "another title: 3 children (source, 2016)",
      "some title: 23rd (source, 2016)",
      "title: 46% (source, 2016)"
    ]
  },
  {
    "name": "chris",
    "date": "1-1-2021",
    "statistic": [
      "some title: 46th (source, 2014)",
      "another title: 92nd (source, 2014)",
      "title: 52.8% women/children (source, 2007/08)"
    ]
  }
]


for (let i = 0; i < arr.length; i++) {
  arr[i].custom = {};
  arr[i].custom["statistics"] = [];
  for (let x = 0; x < arr[i].statistic.length; x++) {
    var s = arr[i].statistic[x].split("(");
    var l = s[0].split(":");
    var u = l[1].split(" ");
    arr[i].custom["statistics"].push({
      number: u[1],
      suffix: u[0],
      label: l[0],
      source: s[1].substr(0, s[1].length - 1)

    });
  }
}
console.log(arr)

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

javascript, contrasting functions and variables

As I delve into the world of Javascript and JQuery (hence why I chose the example below), I have observed an interesting behavior. I noticed that not only can I define a function and call it, but I can also just do something else mysterious by using the do ...

Tips for accessing elements within a jQuery tab

When a user clicks on a tab, I want to be able to access elements inside that tab. $('.myTabs').tabs({ activate: function(event,ui){ console.log("I need to retrieve the contents of the activated tab..."); } }); Just to note, I ...

Eslint in Gulp can't locate my .eslintrc configuration file

My gulp-eslint is unable to locate my .eslintrc file. I've set up a lint task as follows: gulp.task('lint', function () { gulp.src(['src/**/*.js', 'src/**/*.jsx']) .pipe(eslint()) .pipe(eslint.format()); }) The t ...

struggling to extract specific text using Python and Selenium

I need to extract Finance data from a particular div, but there is no specific identifier for it. My current approach involves collecting 3-4 divs and checking if the word FINANSE is present in the text. If it is, I retrieve the inner div text. However, th ...

reveal a hidden div by sliding it during an onclick action

My PHP while loop code is as follows: while (...($...)){ $convid = $row['ID']; echo" <button onclick='getconvo($convid)'>open</button> <div class="convowrap"></div> "; } Here is the correspond ...

Checking the authenticity of Javascript Objects containing date values

What is the best way to validate a JavaScript Object that includes date fields? While there are JSON validators such as tv4 that can check the format of string dates, our business logic operates with JavaScript Date instances which these validators do not ...

developing a do-while loop that terminates upon receiving a designated user input

I am currently working on a project to develop a program that generates receipts for customers. The objective is to prompt users for the item name, price, and quantity, then display the resulting array in an organized format. However, I have hit a roadbloc ...

Creating Outer Glow Effect on a Plane Primitive with THREEJS

Seeking guidance on creating a glow effect for a plane primitive in THREEJS. Found examples for cubes and spheres, but those involve encasing the object inside another transparent material, which is not suitable for my needs. The desired glow effect shoul ...

Having trouble with e.preventDefault() not working on submit() in Javascript?

I'm facing an issue with submitting a form using JavaScript submit() LIVE ACTION : https://jsfiddle.net/98sm3f3t/ HTML : <form id="myForm" action=""> First name: <input type="text" name="fname"><br> <button id="myButton ...

Tips for implementing next-iron-session with personalized api route middleware in NextJS?

Currently, I am working on implementing session storage with next-iron-session and using Firebase for authentication. Every API route requires both the auth middleware and next-iron-session. This is my first time using NextJS and I have tried several appro ...

Combine the non-empty values of two arrays into a single array using PHP

Let's consider this scenario: I have 2 arrays as shown below: <?php $array1 = [ 'key1' => 437776, 'key2' => 'Bar', 'key3' => '' ]; $array2 = [ 'key1' => ' ...

add component automatically upon selection

Imagine I have a special <SelectPicker/> element that allows me to choose an option. What I am trying to figure out is how I can include another <SelectPicker/> once I have made a selection. function DynamicComponent() { const [state, setSta ...

Encountering a cannot POST / error while using Express

I am encountering an issue with my RESTful API while using Postman to call the route /websites. Despite my efforts, I keep receiving the error message "Cannot POST /websites". In addition, I am exploring the implementation of a job queue utilizing Express, ...

Response received from the server

I am looking to display server response error messages within a form after submission. By using the following code in my JavaScript, I am able to retrieve the error message: .error(function (data, status, header, config) { $scope.postDataSuccessfully ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

Having trouble with Bootstrap v4 dropdown menu functionality?

For some reason, I cannot get the dropdown menu to work in my Bootstrap v4 implementation. I have tried copying and pasting the code directly from the documentation, as well as testing out examples from other sources on separate pages with no luck. &l ...

Retrieve the keys stored within a complex array of objects

I am searching for a function that can transform my data, specifically an array of objects with nested objects. The function should only include keys with immediate string/number/boolean values and exclude keys with object/array values. For example: [ { ...

Retrieving a specific element within a nested array located in an object

Currently, I am utilizing knockout.js in my project and facing issues with accessing a specific element from a multidimensional array stored within my viewModel object. Here is a snippet of my code: var viewModel = { states: [ new state("Virgi ...

How can I store all selected dropdown values in the URL parameters whenever a dropdown option is changed?

In mypage.php, I have set up three drop-down menus: <select name='vehicle'> <option value=''>Select</option> <option value='bus'>Bus</option> <option value='bike'>Bike</o ...

Show a property from the local storage as an option in ng-options

Within my Angular application, I keep crucial victim data in local storage. This data is then showcased in the view where it can be altered (via a <select>): <h1>Victim #{{victim.numero}}</h1> <label>Victim status</label> &l ...