generate json within loop

2

I need some help:

I have the following json

var jsonString = "{ \"0%\" : { \"margin-left\":\"-0%\"},";
    jsonString += " \"25%\" : { \"margin-left\":\"-0%\"},";
    jsonString += " \"30%\" : { \"margin-left\":\"-100%\"},";
    jsonString += " \"50%\" : { \"margin-left\":\"-100%\"},";
    jsonString += " \"55%\" : { \"margin-left\":\"-200%\"},";
    jsonString += " \"75%\" : { \"margin-left\":\"-200%\"},";
    jsonString += " \"80%\" : { \"margin-left\":\"-300%\"},";
    jsonString += " \"100%\" : { \"margin-left\":\"-300%\"}}";

jsonString = JSON.parse(jsonString);

$.keyframe.define([
  $.extend(
      { name: 'tocaSlide' }, 
          jsonString
      )
]);

It works for my purposes.

But as it stands, I have a static% var of%.

I need to be jsonString .

So I'm generating it within dinâmico , but it's giving error.

I'd like to know where I'm going wrong.

  var jsonString ={};   

  for (i = 0; i < quantasImagens; i++) {    

  tMin = t + tempoTransicao;
  tMax = t + tamanhoIntervalos; 
  t+=tamanhoIntervalos;

  if(i==0) tMin=0;
  if(i==quantasImagens) tMax=100;         

  jsonString += "'" + tMin + "%' : { 'margin-left':'-" + tempoImagens + "%'],";
  jsonString += "'" + tMax + "%' : { 'margin-left':'-" + tempoImagens + "%'},";

  tempoImagens+=100;

  }


  jsonString = JSON.parse(jsonString );
    
asked by anonymous 29.10.2017 / 21:38

1 answer

2

You can think of "assembling an object" instead of thinking of strings that should be transformed into an object ...

I think what you're looking for would look something like this:

var obj = {};

for (i = 0; i < quantasImagens; i++) {

  tMin = t + tempoTransicao;
  tMax = t + tamanhoIntervalos;
  t += tamanhoIntervalos;

  if (i == 0) tMin = 0;
  if (i == quantasImagens) tMax = 100;

  obj[tMin + '%'] = { 'margin-left': '-' + tempoImagens + '%'};
  obj[tMax + '%'] = { 'margin-left': '-' + tempoImagens + '%'};
  tempoImagens += 100;
}


console.log(obj);

Note: the if (i == quantasImagens) tMax = 100; condition will never be reached because the loop will stop when i < quantasImagens .

    
29.10.2017 / 21:44