Continuously inserting new records to a JSON file using a while loop

Is there a way to continuously add key value pairs to a JSON object within a while loop?

var sName = "string_";
var aKeys = ["1", "2", "3"];
var sKey = "key";
var n = 1;
var aObj = {};

var l = aKeys.length;
for(let i=0; i < l; i++){
   while(n < 5)
  {
    n += 1;
    aObj.sKey = sName.concat(n);
  }
}
console.log(JSON.stringify(aObj));

expected output:

{"sKey":"string_2", "sKey":"string_3", "sKey":"string_4"}

Answer №1

It's important to note that Object cannot contain duplicate keys. Give this a try:

var value = "string_";
var key = "key_"
var count = 1;
var obj = {};

while(count < 5)
{
  obj[key.concat(count)] = value.concat(count++);
}

console.log(JSON.stringify(obj));

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

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...

Getting the ID of a button: A step-by-step guide

My query involves a file named Index.aspx connected to another file called seatbooks.js. Within Index.aspx, there is a button with the id Indexbutton. This button has an eventonclick='book_ticket()' attribute. The book_ticket() method is includ ...

Why is my date appearing in the format /Date(1640035318903)/ when retrieved from the controller in C#?

After requesting my records from the server in C#, I noticed they are coming back in a specific format: (viewed through the network tab / preview on the network call) DateModified: "/Date(1640035318903)/" https://i.sstatic.net/jy6MT.png What ...

Ways to receive alerts when a marker enters a polygon

Looking for a way to receive notifications if my marker enters any of the polygons on the map. Having trouble implementing it correctly, here is my current code: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com ...

What is the best way to convert JSON to a Java object while utilizing the RequestBody interface in a RESTful API call?

Here is the project structure for a Maven project I am working on: Project 1 -> Core-part (containing interfaces): interface Foo{ public String getStr1(); public setStr1(String str1); public List<? extends Bar> getBarList(); pub ...

What steps can be taken to further personalize this pre-existing jQuery sorting solution?

After coming across a solution for adding sorting capabilities to jQuery (source: jQuery sort()), I decided to tweak it to handle strings of variable lengths. Although the modified function sorts in ascending order, I found it quite effective. jQuery.fn.s ...

add the elements of an array to multiple div elements sequentially

I'm attempting to update all titles in .item with the values from array. The array I am using contains the following elements: var itCats = ['one', 'two', 'three', 'four']; Additionally, this is the HTML struc ...

Using regular expressions to add a string before each occurrence

I have scoured numerous resources and forums but couldn't find a suitable solution for my problem. Since I am not well-versed in this topic, I am reaching out to the experts for assistance. This is the extent of what I have accomplished so far: This ...

Nginx forwards static content to a subdirectory within the main root directory

I have an application running at http://192.168.0.2:8080/. The main index.html page is located in the /web directory and it fetches static files, such as css, from the /css folder. My aim is to use nginx as a reverse proxy to redirect myapp.mydomain.com t ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...

Error VM5601:2 encountered - Unexpected token "<" found in JSON at position 10

I am trying to retrieve data using Ajax and jQuery, but I keep encountering an error that I cannot figure out how to fix. VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10 Below is the code I am working with. Model public f ...

Can TypeScript be used to dynamically render elements with props?

After extensive research on SO and the wider web, I'm struggling to find a solution. I have devised two components, Link and Button. In short, these act as wrappers for <a> and <button> elements with additional features like chevrons on t ...

The Google Javascript API Photo getURL function provides a temporary URL that may not always lead to the correct photo_reference

Currently, I am integrating Google Autocomplete with Maps Javascript API into my Angular 5 application. As part of my website functionality, I fetch details about a place, including available photos. The photo URL is obtained through the getURL() method. ...

Error in AJAX transmission

I am encountering an unusual issue with the jQuery ajax function in my script. The problem is specific to my friend's computer, as I am not experiencing any difficulties on my own computer. While attempting to utilize the error function property to ...

Clearing FullCalendar events when the month button is pressed: A step-by-step guide

What is the best way to hide ONLY events on a calendar? I was considering deleting all events when the user clicks the "month" button. How can I achieve this functionality? $scope.uiConfig = { calendar: { height: 450, editable: false, ...

Endlessly scrolling text using CSS

Is it possible to create a continuous rolling text effect on an HTML page without any gaps, similar to a ticker tape display? For example, displaying "Hello World ... Hello World ... Hello World ... Hello World ..." continuously. I attempted using the CSS ...

The data from the REST API is not being rendered accurately within the ReactJS application

I'm currently working on a React application that enables users to select movies from a list fetched from a REST API I developed. Once a movie is selected, the corresponding URL, as provided in the JSON API, is displayed. Despite researching various r ...

Struggling with React Js and need some assistance?

I'm completely new to React Js and encountering issues with my code. Here's what I have: Here is the content of my script file named Main.jsx. This file gets compiled by React, and the output is stored in main.js under the 'dist' folde ...

Decoding a JSON with Gson: Unraveling the Data

I have received a JSON data from a server with a specific syntax that I need help deserializing and parsing. I've done research and discovered that using GSON would be very helpful! (I'll update my code here) (Corrected JSON): [{ "name" ...

Is there a way to customize the CSS for a single blog post and add a 5-star rating system without affecting other posts?

After launching my blog on Google's Blogger, I wanted to add a unique touch by incorporating a static 5-star rating system in my Books I Read Section. I thought about using CSS to customize each book post and display anywhere from 1 to 5 stars for vis ...