Incorporating interactive elements and expanding rows within a multidimensional JSON array using AngularJS

I've got an array of JSon objects structured like this:

var myObject= [
{"name":'Tom', "city":'Chicago',"GroupCode":'1'}, 
{"name":'Harry', "city":'Wisconsin',"GroupCode":'1'}, 
{"name":'Rob', "city":'Los Angeles',"GroupCode":'2'}, 
{"name":'Peter', "city":'Seattle',"GroupCode":'2'}, 
{"name":'Dave', "city":'New York',"GroupCode":'3'}, 
{"name":'Steve', "city":'Boston',"GroupCode":'3}
];

I need to insert a new row with placeholder values whenever the GroupCode changes. I want my array to look like this:

var myObject= [
{"name":'Tom', "city":'Chicago',"GroupCode":'1'}, 
{"name":'Harry', "city":'Wisconsin',"GroupCode":'1'}, 
{"name":'--', "city":'--',"GroupCode":'--'}, 
{"name":'Rob', "city":'Los Angeles',"GroupCode":'2'}, 
{"name":'Peter', "city":'Seattle',"GroupCode":'2'}, 
{"name":'--', "city":'--',"GroupCode":'--'}, 
{"name":'Dave', "city":'New York',"GroupCode":'3'}, 
{"name":'Steve', "city":'Boston',"GroupCode":'3} 
]; 

Any ideas on how to achieve this? Your help would be greatly appreciated!

Answer №1

Here is a way to achieve the desired outcome:

let people = [
  {
    "name": 'Alice',
    "city": 'New York',
    "GroupID": '1'
  },
  {
    "name": 'Bob',
    "city": 'Los Angeles',
    "GroupID": '1'
  },
  {
    "name": 'Charlie',
    "city": 'Chicago',
    "GroupID": '2'
  },
  {
    "name": 'David',
    "city": 'Seattle',
    "GroupID": '2'
  },
  {
    "name": 'Eve',
    "city": 'Boston',
    "GroupID": '3'
  },
  {
    "name": 'Frank',
    "city": 'Miami',
    "GroupID": '3'
  }
];
// store the first group ID
let firstGroup = people[0].GroupID;
people.forEach(function(person, index) {
  if (firstGroup !== person.GroupID) {
    firstGroup = person.GroupID;
    // insert placeholder object
    people.splice(index, 0, {
      "name": '---',
      "city": '---',
      "GroupID": '---'
    });
  }
})
console.log(people)

Try out the code here

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

Is an object of array type always declared by T D[N]?

I'm feeling a bit puzzled regarding [dcl.array]/1: When we have a declaration T D where D is in the form           D1 [ maybe-constant-expressionopt ] optional-attribute-specifier-sequenceopt and the type of the identifier in the declarati ...

What is causing this issue with my jQuery UI animation?

Below is the HTML code snippet: <div id="menu_status_item"> <span class="menu_status_bar"></span> </div> Here is the CSS code: #menu_status_item { margin-top: 40px; width: 100%; } .menu_status_bar { margin-le ...

Creating a div that becomes fixed at the top of the page after scrolling down a certain distance is a great way to improve user experience on a

I am struggling to create a fixed navigation bar that sticks to the top of the page after scrolling 500px, but without using position: fixed. Despite trying various solutions, none seem to work due to the unique layout of my navigation bar. Strangely enoug ...

Tips for ensuring the Google Maps API script has loaded before executing a custom directive on the homepage of an Angular website

Issue - I am facing issues with Google Maps autocomplete drop-down not working on my website's main page even after parsing and loading the Google Maps API script. The problem seems to be a race condition on the main page of my website, specifically i ...

Using AngularJS and ASP.NET MVC to acquire files for download

Hello, I am new to developing with asp.net mvc and currently working on a project that involves downloading files such as images and pdfs. Below is the code snippet I have been using: Snippet from the asp controller: [HttpPost] public HttpRespons ...

Difficulties with validating phone numbers

I'm having an issue with my JavaScript code that is supposed to validate a phone number field, but it doesn't seem to be working. Even if I enter incorrect values, the form still submits. Here's the snippet of my code: <script> functi ...

issue with vue-html2pdf when using Persian language

Is there a solution for handling Persian language issues in vue-html2pdf? Or is there another module that can convert VUE to PDF without any problems with RTL language support? ...

Show the result of file upload, whether it was successful or not, using ReactJS

I need to implement an Ajax call for uploading a file to the server. I want to display success and failure messages based on the outcome of the file upload process. $.ajax({ url: "https:my_url", data: {my data: my_data}, method : "POST", success: ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

Troubleshooting error in data structure for nested dynamic routes with Next.js getStaticPaths

I am working on a page called [categories][price].js and I am attempting to achieve a particular data structure within the getStaticPaths function. For example, I want to have paths like cat1/10, cat1/20, cat1/30, cat2/10, cat2/20, etc. I came across this ...

What could be causing my THREE.js Documentation Box to malfunction?

I am a newcomer trying to get the hang of THREE.js. I delved into the THREE.js Documentation and attempted to implement the code, but when I loaded my HTML page, it appeared blank. I am at a loss for what to do next. I utilized Visual Studio Code for codin ...

Challenges with synchronizing the scope of global arrays when reading JSON files into objects

I'm attempting to load a JSON file into a global array of objects. The code appears to be functioning correctly, however, I am encountering difficulty extracting the data from the Ajax $.getJSON call and storing it in the global variable. This issue c ...

Transform JavaScript code into HTML using jQuery.`

I have a piece of HTML and JavaScript code. The JavaScript code is currently in jQuery, but I want to convert it to vanilla JavaScript: // Vanilla JavaScript code document.querySelectorAll('.hello[type="checkbox"]').forEach(item => { item ...

TextAngular failing to replace &nbsp character

I am currently using textAngular within a div that has a character counter feature. However, I have encountered an issue where a space ( ) is being counted as 6 characters instead of just one. Despite trying various regex patterns to convert this spec ...

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

the specified computed property does not have a value assigned

Issue with the Computed name Property in a Component <template> <div class="person"> <p>{{name}}</p> </div> </template> <script> export default { name: 'person', data () { return ...

When I use the AngularJS otherwise function, it sends me to the incorrect route

My routes are defined in the following way: $routeProvider .when('/settings', { templateUrl: 'settingsTemplateURL', controller: settingsCtrl }) .when('/profile', { templateUrl: 'profileTemplateURL', controll ...

I am getting text content before the input element when I log the parent node. What is causing this issue with the childNodes

Does anyone know why 'text' is showing up as one of the childNodes when I console.log the parent's childNodes? Any tips on how to fix this issue? <div id="inputDiv"> <input type="text" id="name" placeholder="Enter the nam ...

Select a picture at random from a directory

As a student embarking on an art project, I am in the process of selecting one out of 500 images to display on a webpage. My coding knowledge is quite limited, primarily focused on HTML and CSS, with only a basic understanding of JavaScript. I am encounter ...

Issue with automatic form submission

What is the best way to automatically submit my form once the timer runs out and also when the refresh button is clicked? I have encountered an issue where every time I try to refresh the page, it prompts for user confirmation. If I click cancel, it stay ...