Iterating through circular objects in a javascript for loop

My aim is to iterate through the data and generate the following output:

[
{
  odds: "2/3",
  position: 1,
  terms: "1/5"
},
{
  odds: "4/1",
  position: 1,
  terms: "1/7"
}
]
<script>
    var res = '{"count":"2","bettype":"double","position[0]":"1","oddsa[0]":"2","oddsb[0]":"3","placeodds[0]":"1/5","position[1]":"1","oddsa[1]":"4","oddsb[1]":"6","placeodds[1]":"1/7"}';

var line = {};
//
var getvals = JSON.parse(res);
var count = parseInt(getvals["count"]);

var i = 0;
const array = [];//new Array();
for(var i = 0;i < count;i++)
{
line["odds"] = getvals["oddsa["+i+"]"]+'/'+getvals["oddsb["+i+"]"];
line["terms"] = getvals["placeodds["+i+"]"];
line["position"] = getvals["position["+i+"]"];
array.push(line);
}
console.log(array);
  </script>

Unfortunately, I receive a different result from the code above:

[{
  odds: "4/6",
  position: "1",
  terms: "1/7"
}, [circular object Object]]

I don't have much experience with JavaScript coding, so I'm learning as I progress. Despite looking at other examples, I'm still facing some challenges.

Answer №1

Make sure to create a fresh line object every time the loop iterates. Otherwise, you will be repeatedly pushing and modifying the same object reference in the array.

var result = '{"count":"2","bettype":"double","position[0]":"1","oddsa[0]":"2","oddsb[0]":"3","placeodds[0]":"1/5","position[1]":"1","oddsa[1]":"4","oddsb[1]":"6","placeodds[1]":"1/7"}';


//
var values = JSON.parse(result);
var count = parseInt(values["count"]);

var i = 0;
const newArray = []; //new Array();
for (var i = 0; i < count; i++) {
  // initialize a new object here
  var lineObj = {};
  lineObj["odds"] = values["oddsa[" + i + "]"] + '/' + values["oddsb[" + i + "]"];
  lineObj["terms"] = values["placeodds[" + i + "]"];
  lineObj["position"] = values["position[" + i + "]"];
  newArray.push(lineObj);
}
console.log(newArray);

Answer №2

The scenario with the second "what do you want" object doesn't result in 4/1 as expected due to the values of oddssa[1] being 4 and oddsb[1] being 6, resulting in 4/6.

Your overall logic shows promise, so keep it up! Once an object was specified inside the loop, the anticipated outcome was achieved.

To enhance clarity, I have tidied up the code by introducing template literals (backticks) for concatenation instead of using pluses, utilization of proper variable declaration (such as const/let over var), and updated calling property to getvals.count for consistency.

const res = '{"count":"2","bettype":"double","position[0]":"1","oddsa[0]":"2","oddsb[0]":"3","placeodds[0]":"1/5","position[1]":"1","oddsa[1]":"4","oddsb[1"":"6","placeodds[1]":"1/7"}';

const getvals = JSON.parse(res);

const count = parseInt(getvals.count);

const arr = [];

for(let i = 0;i < count;i++) {
  const line = {
    odds: getvals[`oddsa[${i}]`] + "/" + getvals[`oddsb[${i}]`],
    terms: getvals[`placeodds[${i}]`],
    position: getvals[`position[${i}]`]
  }
  arr.push(line)
}

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

Emulating the functionality of React's useState in vanilla JavaScript and Node.js

Seeking a way to retrieve the state value from this simulated Vanilla JS useState function: let callIndex = -1 const stateValues = [] const useState = (initialValue) => { callIndex++ // 0 const currentCallIndex = Number(callIndex) // 0 i ...

Unusual browsing patterns in angularjs when using the ionic framework

Check out this demo I am able to navigate from page 1 to page 2 using the link: <a href="#/threadContent">GO</a> However, I am having issues getting back from page 2 to page 1 using <a href="#/home">Back</a>. I'm curiou ...

I'm having trouble getting my placeholder to display correctly in react-native-datepicker. What could be the issue?

I'm struggling with displaying a placeholder correctly in the datepicker package I'm utilizing for react native... This is how I've configured the component: The _onDateChange function: const _onDateChange = (startTime) => { pickDa ...

Will cancelling a fetch request on the frontend also cancel the corresponding function on the backend?

In my application, I have integrated Google Maps which triggers a call to the backend every time there is a zoom change or a change in map boundaries. With a database of 3 million records, querying them with filters and clustering on the NodeJS backend con ...

The concept of undefined does not hold any tangible form

TypeError: undefined is not an object (evaluating 'this.props.data.map') appContent: displayData(){ let info = this.props.data.map(function(dataItem, index) { return ( <Card> <CardItem> <Body ...

Issues with displaying Angular Material's ng-messages in a dialog box

While working on a login form within a dialog, I noticed that the ng-messages for the respective input are not appearing. The validation is functioning properly as the input turns red when there's an error, and the button remains disabled until the va ...

Assigning values to a 3D array

Is it possible to streamline the process of assigning values in a 3D array in Java? If so, how can this be done? int [][][]array = new int[3][][]; array[0] = new int [4][5]; array[1] = new int [5][5]; array[2] = new int [3][5]; ar ...

pause in execution between iterations of a for loop

Challenge I'm currently working on a function that processes a list of strings by printing each one on a new line, with CSS animations that gradually display the string over a few seconds. However, I'm struggling to make sure that the next strin ...

Using ReactJS to Apply Map and Filter Functions to JSON Data via Props

Struggling with a perplexing issue that seems trivial. Can't seem to find the right solution... I've got a db.json file structured like this: { "applicants": [{ "id": 1, "firstName": "John", "lastName": "Doe", "email": "& ...

Exploring the wonders of fs.readdir, fs.readfile, and the power

This application is built on Node with an express server. It contains a directory filled with text files, and the goal is to extract lines that contain the word "SAVE" from each file. Unfortunately, I've hit a roadblock in this process. app.get(&apo ...

The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript: var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800 ...

How can I remove specific items from a session array when they are selected?

I am seeking a solution that will allow me to remove a specific item from an array when that item is clicked. For example, if I click on "Two", it should disappear. See a demonstration here: CODE: <form method="post"> <input type="text" i ...

What's the best way to switch between pages in NextJS using radio buttons?

I'm currently developing a NextJS project and have implemented a side navigation bar for user interaction. To give users a clear visual indication, I decided to use a radio button group. The idea is that when a user selects one of the options, the cor ...

gulp-webpack encountered an error: The entry module could not be found. Error: module resolution failed

Whenever I attempt to run gulp scripts, it gives me the following error message: ERROR: Entry module not found Error: Unable to resolve 'C:/Users/milan/Local Sites/project-university/app/public/wp-content/themes/fictional-university-theme/js/scrip ...

Tips for effectively using the parseInt function to access and verify a span element from inside a chrome extension

Trying to utilize parseInt to ascertain if a span element is greater than or equal to 1 within my Google Chrome Extension. Attempting to monitor this "0" for changes and trigger a specific URL upon change - Refer to the Image View of the "inspect" option ...

Encountering the error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" while attempting to identify duplicate entries in my database

I am currently working on a backend written in express.js that handles standard CRUD operations. My ORM of choice is sequelize. Here's the code snippet: import { Sequelize} from 'sequelize'; import User from '../Models/User.js'; im ...

Incorporate a globally imported class inside a Vue 3 component by utilizing the provide function

In the process of developing an application using Vue 3, I have created an api class specifically for handling API calls: import axios from 'axios' export default class { /** * Send GET Request * @param {string} url * @retur ...

Is there a method to accurately detect the rendering of individual elements within a React Component, rather than the entire component itself?

While it's known that Components rendering can be detected through React's Developer Tool, I came across other methods in this source. However, what I'm specifically interested in is detecting the rendering of individual elements within a Co ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

Issues with conditional statements not properly executing in ASP.NET when using onclick and onselect functions

I've been stuck on this issue for over a day now and can't seem to figure out why my code isn't working. I'm creating a web page in ASP.NET and trying to implement a text box with gray placeholder text that changes to black when clicked ...