anson920520 anson920520 - 1 year ago 85
Javascript Question

Javascript: Pushing data to an array object inside for-loop

For example I have an object looks like below.

I am push these already

for(var i = 0; i < result.length ; i++){

var test3way = [
{y: engagementPercentage[0], numData : engagaement[0], id: sovId[0]},
{y: engagementPercentage[1], numData : engagaement[1], id: sovId[1]},
{y: engagementPercentage[2], numData : engagaement[2], id: sovId[2]},
{y: engagementPercentage[3], numData : engagaement[3], id: sovId[3]},
{y: engagementPercentage[4], numData : engagaement[4], id: sovId[4]}

And i tried to use for loop to prevent duplicate

for(var i = 0; i < engagementPercentage.length ; i++){

var test3way = [
y: engagementPercentage[i],
numData : engagaement[i],
id: sovId[i]

But it doesn't looks like i am doing in right apporch, how should i correct it?

P.S Consider those arrays are look like
var sovId = [1,56,23]

Answer Source

Your code only defines test3way variable multiple times and having different property values each iteration of the loop. You can try array pushing.

var test3way = [];
for (let i = 0; i < engagementPercentage.length ; i++) {
         y: engagementPercentage[i],
         numData : engagement[i],
         id: sovId[i]

Also on a side note, you should write let i instead of var i as the for loop iterator so that the scope is only within the loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download