A method for determining the number of JSON objects present, and utilizing that count to generate a corresponding output

  1. Is there a way to calculate the total number of JSON objects in the array and then recreate the same output based on that count?

        var obj = 
       [
        {"id":"0","name":"Mike Johnson","group":1},
        {"id":"1","name":"Bob Smith","group":2},
        {"id":"2","name":"Richard Thomas","group":3},
        {"id":"3","name":"Betty White","group":16},
        {"id":"4","name":"Tim Thompson","group":3},
        {"id":"5","name":"Carl Lewis","group":16},
        {"id":"6","name":"Kathy Towers","group":3},
        {"id":"7","name":"Billy Bob","group":1},
        {"id":"8","name":"Sally Bailey","group":1}
        ];
    
    1. First, I'd like to determine the count, and then recreate the output based on that count. The desired output should match the original input. for Count:-

      var count = 0;
      function getCount() {
      
      for (var i = 0; i < obj.length; i++) {
      
              count++;
      
      }
      return count;
      }
      

    for output :-

    function showDetails()   this is not giving the proper output
    { 
    
       for(var j=0; j< count; j++){ 
       obj.push([{j}]);    
       }                   
    alert(obj.name);        
    }                      
    alert(showDetails());   
    And I want an output like:- 
    
         var obj = 
       [
        {"id":"0","name":"Mike Johnson","group":1},
        {"id":"1","name":"Bob Smith","group":2},
        {"id":"2","name":"Richard Thomas","group":3},
        {"id":"3","name":"Betty White","group":16},
        {"id":"4","name":"Tim Thompson","group":3},
        {"id":"5","name":"Carl Lewis","group":16},
        {"id":"6","name":"Kathy Towers","group":3},
        {"id":"7","name":"Billy Bob","group":1},
        {"id":"8","name":"Sally Bailey","group":1}
        ];
    

    Does anyone know how to help me with this?

Answer №1

let months ="January,February,March,April,May,June,July,August,September,October";
let monthArray = months.split(',').map((month)=>{
     return {
           name: month
           }
});

The variable monthArray will contain the desired output

Answer №2

let months = "January,February,March,April,May,June,July,August,September,October";

let monthArray = months.split(',').map(function(month) {
 return {name: month};
});

console.log(monthArray);

Answer №3

let monthString = "January,February,March,April,May,June,July,August,September,October";
let monthsArray = monthString.split(",");
let finalResult = [];


for (let index in monthsArray)
{
   let singleMonth = {};
   singleMonth.name = monthsArray[index];
   //additional operations can be performed here, for example:
   //singleMonth.numberOfDays = 31;
   finalResult.push(singleMonth);
}

Answer №4

If you want to achieve a similar result, you could consider the following approach:

let words = sentence.split(" ");
let modifiedWords = [];

words.forEach(function(word){

   let newObj = {
        term: word
   }

   modifiedWords.push(newObj);

});

console.log(modifiedWords);

Answer №5

Link to MDN reference

To split a string into an array, you can use var array = string.split(',');

Answer №6

This is an enhanced ES2015 approach that leverages constants, arrow functions, and implicit return statements.

const monthsString = 'January,February,March,April,May,June,July,August,September,October';
const monthArray = monthsString.split(',').map(name => ({name}));
console.log(monthArray);

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

The Three.js Raycaster gets thrown off when scrolling through the page

When a scene does not display entirely on the page and you can scroll, the Raycaster stops working and is affected by the scrolling offset. If you scroll to the side by 20 pixels down, you need to have 20 pixels below the object for the click to be recogn ...

Chrome App Experiencing Issues with DOM Loading

I am working on converting a simple HTML5 Snake game that utilizes canvas into a Chrome App. Below is the snippet of my original HTML file: <!DOCTYPE html> <html> <head> <title>Snake</title> <link rel=" ...

Using JavaScript to dynamically populate a popover with content

Struggling to incorporate a button into my popover using JS. The plan is to eventually create these buttons with PHP, but something seems amiss. <div class="col-1"> <a data-toggle="popover" id="bedsButton" data-plac ...

Vue.js: Why Objects are Returning 'Undefined' Values in Arrays

Attempting to improve my JavaScript OOP skills, I am also delving into learning vue.js. My current project involves creating a simple task list for practice purposes. While most of it is complete, I have hit a roadblock with the remove task function. Initi ...

Utilizing Angularfire OAuth for Facebook authentication in login strategy

After successfully implementing the code below in the loginCtrl controller and login.html, I encountered some issues with setting up the workflow correctly. My goal is to achieve something like this: //check if the current $scope has authData //if so red ...

Tips on using b-table attributes thClass, tdClass, or class

<template> <b-table striped hover :fields="fields" :items="list" class="table" > </template> <style lang="scss" scoped> .table >>> .bTableThStyle { max-width: 12rem; text-overflow: ellipsis; } < ...

Shifting listbox items + Postback or callback argument is not valid

My listbox contains 2 buttons to move items up and down. When shifting the position of pre-bound items, everything functions as expected. However, if I try to add a new item from a textbox, shift its position, and then save the form, an error arises. The e ...

What is the method to retrieve the image's value after dropping it onto the droppable area?

I have implemented a drag and drop feature using jQuery, and I am trying to extract the value of an image and insert it into a database. Additionally, I want to update and remove the image value when it is removed from the droppable area. How can I achie ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

Load divs, images, or scripts as they enter the viewport

Upon visiting the website , you may notice that certain elements are loaded only when they enter the viewport. I am interested in learning how to implement this feature and am curious about the specific JavaScript or CSS3 techniques utilized for achieving ...

Troubleshooting the rendering issue with Angular5 observables in displaying the list

I've been exploring Observable in angular5 and I'm facing an issue with my code. Component.ts file export class CommerceComponent implements OnInit { public List$: Observable<any>; getData(id){ this.List$ = this.gateway.search(id); ...

Combining two sets of JSON data through mathematical operations

Two JSON files are available: one containing team names and codes, and the other with match details and scores. The goal is to create another JSON file that aggregates total matches won-lost and total goals. The JSON files are located at: JSON 1 ...

Text field value dynamically changes on key press update

I am currently working on the following code snippet: {% for item in app.session.get('aBasket') %} <input id="product_quantity_{{ item['product_id'] }}" class="form-control quantity" type="text" value="{{ item['product_quan ...

Utilizing Functions within Arrays and Exploring Time Intervals for Optimization

I am currently working on a game development project where the game involves answering questions within a specific time frame. Each question should be answered within 10 seconds before resetting for the next one. I'm fairly new to JavaScript and would ...

Trouble with JavaScript loading in HTML webpage

<!DOCTYPE html> <html> <head> <title>Breakout Game</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <canvas width="900" height="450" class="canvas"></canvas> ...

Passing data from a child component to a parent component in Vue 3: How

Struggling with Vue 3 app authentication through event-emission from child to parent. Below is a snippet of the code: Child <template> <form class="msform"> <input @click="goToLogin" type="button" name=&q ...

Creating dynamic select boxes in Django Admin using jQuery

In my Contract class, the contract_mod field is designed to extend a contract from a previous one and should only display contracts related to the selected person. The Contract class returns the person field, but since I have no experience with AJAX/jQuery ...

Creating hyperlinks for objects in three.js can be achieved by using the

Here is the code from my firstpage.js file: $(function(){ /* initializing variables */ var scene, camera, renderer; var spotLight, hemi; var SCREEN_WIDTH, SCREEN_HEIGHT; var mouse var loader, model, animation; var objects = []; function init(){ / ...

Is it possible to view a file written in Vuejs as a valid JSON-compliant object definition

As a beginner in vuejs, I have noticed a specific structure present in .vue files. export can be considered as a compliant JSON structure. Also, I am wondering about the significance of data() function without an associated property name. Similar styles ...

Using JavaScript to create a timer

How should I go about implementing basic timer functionality? Should I use a for loop, or is there another loop that could work better? I want to print the value of x in the function "hello()" after creating a 30-second delay. I'd like it to print so ...