Navigating JSON data with Angular and populating any gaps in the information

Recently, I encountered a challenge where I needed to populate a range input using data extracted from an external json file...

The data consists of multiple objects with arrays of values and corresponding text. However, some of these objects have non-consecutive values that disrupt the loop required for outputting on the range slider as shown below:

var someObj = [
  {
    value: 1,
    text: 'A'
  },
  {
    value: 2,
    text: 'B'
  },
  {
    value: 3,
    text: 'C'
  },
  {
    vaule: 5,
    text: 'D'
  },
  {
    value: 6,
    text: 'E'
  },
  {
    vaule: 8,
    text: 'F'
  }
];

As you can see, Value: 4 and value: 7 are missing. This inconsistency extends to other objects where values such as 11 and 13 might be missing.

My goal is to iterate through each object and fill in missing values by duplicating the text value from the preceding value like this:

var someObj = [
  {
    value: 1,
    text: 'A'
  },
  {
    value: 2,
    text: 'B'
  },
  {
    value: 3,
    text: 'C'
  },
  {
    vaule: 5,
    text: 'D'
  },
  {
    value: 6,
    text: 'E'
  },
  {
    vaule: 8,
    text: 'F'
  }
];

The updated array would look like this:

var someObj = [
  {
    value: 1,
    text: 'A'
  },
  {
    value: 2,
    text: 'B'
  },
  {
    value: 3,
    text: 'C'
  },
  {
    value: 4,
    text: 'C'
  },
  {
    vaule: 5,
    text: 'D'
  },
  {
    value: 6,
    text: 'E'
  },
  {
    vaule: 7,
    text: 'E'
  },
  {
    vaule: 8,
    text: 'F'
  }
];

I am curious if it's possible to achieve this task and if so, what approach should I take? Your insights would be greatly appreciated!

Thank you in advance

Answer №1

let counter = 0;
do{
if(someObject[counter].value !== counter+1){
    let object = {}
    debugger;
    object['value']= counter+1;
    object['text']= someObject[counter-1].text;
    someObject.splice(counter,0,object);
}
counter++;

}while(counter < someObject.length);

Check out this link for reference:https://jsfiddle.net/cw5kkpgu/

Answer №2

Retrieve the value of the final object using the following method:

var lastObjectValue = someObj[someObj.length-1].value;

Next, utilize a loop to compare values and insert missing ones:

for(i = 0; i < lastObjectValue-1; i++) {

    if(someObj[i].value != (i+1)){

        someObj.splice(i, 0, {value: i+1, text: someObj[i-1].text})

    }

}

Answer №3

I've developed a JavaScript function to fill in the missing objects within an array. Please let me know if it meets your requirements.

function completeObject(someObj)
{
    var otherObj = [];
    for(var obj in someObj)
    {
      otherObj[someObj[obj]['value']] = someObj[obj];
    }

    var j = 0;
    for(var i =1 ; i <= someObj[someObj.length-1]['value'];i++)
    {
      if(otherObj[i] === undefined)
      {
        var obj = {}
        obj['value']= i;
        obj['text']= otherObj[j]['text'];
        otherObj.push(obj);
      }
      else
      {
        j = i ;
      }
    }

    return otherObj;
}

Answer №4

Finally, I have managed to solve the problem at hand. Initially, there was some confusion regarding your requirements, but now everything should be clear. Here is the Plunker link for reference:

http://example.com/plunker123

Kindly verify if this meets your expectations.

The key concept behind the solution is as follows:

$scope.loop = function(){
  var previousText = '';
  var previousValue = '';
  var newObject = [];

  angular.forEach($scope.someObj, function(object){

    if(object.value == 1){
      newObject.push(object);
      previousText = object.text;
      previousValue = object.value;
      console.log("value:" + previousValue + " | Text:" + previousText);
    }
    else {
      if(object.value != (previousValue + 1)){
        while (object.value != (previousValue + 1)){
            previousValue += 1;
            newObject.push({ value: previousValue, text: previousText})

            console.log("value:" + previousValue + " | Text:" + previousText);
        }
      }
      else{
            newObject.push(object);
            previousValue = object.value;

            console.log("value:" + previousValue + " | Text:" + previousText);
      }

      previousText = object.text;
    }

  });

  // Add the last value as it's always missed
  newObject.push($scope.someObj[$scope.someObj.length - 1])

  $scope.someObj = newObject;
}

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

Issues with triggering onScroll event in Internet Explorer 11

<html> <head> <style> div {`border: 1px solid black; width: 200px; height: 100px; overflow: scroll;` } </style> </head> <body> <p>Experience the magic of scrollbar within ...

What is the best way to clear an input value in Vuejs after it has been submitted?

Could you help me with my to-do list in Vuejs? I'm having trouble resetting the input value when a new item is added. Any suggestions on how to achieve this? I've attempted to retrieve the input value and set it to an empty string, but unfortuna ...

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

Dealing with PhantomJS: Tackling the Challenge of XMLHttpRequest Exception 101 Error

As a newcomer to JavaScript and PhantomJS, I have been encountering an issue when running myfile.js (which involves for loops) with the command phantomjs myfile.js. It consistently throws the error: NETWORK_ERR: XMLHttpRequest Exception 101: A network err ...

Guide on updating a variable to the following string within an array

Snippet: months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October&apos ...

Exploring the Process of Printing Python Dictionaries

There is a Python dictionary named top_words. To print its contents, I have used the following code snippet. for word, count in top_words.items(): print(word, count) This displays something like shown in the image at this link. I am trying to figu ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

Guide on extracting and displaying the JSON data associated with a specific ID from a JSON file in Python

There is a json file containing the following data: { "A": "ID", "B": "Priority", "C": "Match URL", "D": "Match Query", "E": "Redirect URL", ...

What is the best way to loop through a MongoDB collection using mongojs?

In my current project, I am utilizing the mongojs library and facing an issue while attempting to iterate through all elements in a collection. index = 0 db.keys.find({}, {uid: 1, _id: 0}).forEach((err, key) => if err? console.log err ...

Replacing JS/CSS include sections, the distinction between Debug and Release versions

Can you share how you manage conditional markup in your masterpages for release and debug builds? I am currently using the .Net version of YUI compress to combine multiple css and js files into a single site.css and site.js. One idea I had was to use a u ...

Error: Trying to access a property that is not defined (reference to 'user')

import { createSlice } from '@reduxjs/toolkit'; export const userSlice = createSlice({ name: 'user', initialState: { user: null, }, // The `reducers` field allows us to define reducers and generate associated actions redu ...

The simultaneous triggering of two button events is not occurring in a TypeScript environment

I have a situation where I have 2 buttons positioned next to each other: Current year PR signature and Prior year PR signature Upon clicking on either the Current year or Prior year PR signature button for the first time, it successfully retrieves and dis ...

Scroll through the div to quickly find the relevant content

I have implemented the following HTML structure: <div style="height:200px;overflow-y:scroll;"> <table>.....</table> </div> By using this setup, I am aiming to replicate the functionality of an expanded <select> control wit ...

Identifying the presence of a property value within a collection of objects

I am trying to verify the existence of a 'member' object with a specific 'ID' in the 'members' array of an 'EntityGroup' container object. I'm having trouble understanding why the EntityGroup.idExists(id) method ...

Translate Arabic numerals into English as you type

When using Firefox and Safari with an Arabic keyboard, the numbers are input in a format like ٨٦٥ instead of the English format (8754). Is there a way to convert this format while the user is typing in the field, or to prevent non-English formats from ...

Compare the content of two files with different formats, one in TXT and the other

I have two files with similar data in JSON and TXT formats, file-A.json and file-B.txt. The challenge is to compare the records in both files to check for matches or discrepancies. Converting the data into a common format seems like a logical solution, but ...

Why is my webpage attempting to refresh every time I send an AJAX request?

I have been struggling to send a form using AJAX, but no matter how many times I use e.preventDefault(), the page still tries to reload. Here is my HTML: <form action="/user/changeProfileData" id="edit-profile_form" method="post"> <ul class=& ...

Unable to style Backbone View with CSS

Recently started diving into the world of Backbone, and it seems like I might be missing a key concept here. In my View object, there's a snippet of code that's puzzling me... First off, I can't figure out why the CSS change in the highli ...

What is the best way to extract JSON values for use with form controls?

When receiving a JSON response from the server, I need to extract the metadata necessary to construct a FormGroup object. Because both the JSON data and the FormGroup object are dynamic, I am unsure of how to parse the JSON fields in HTML. I examined the ...

Troubleshooting IntelliSense issues in VS Code when using webpack bundles

I am facing an issue with my webpack configuration. Here is a snippet of the setup: const path = require('path'); module.exports = { devtool: 'source-map', entry: './src/index.js', output: { libraryTarget: 'co ...