Pregunta

I have a string compared to this:

{
    "objects": [{
        "originY": "top",
        "left": 0,
        "top": 0,
        "width": 118.33,
        "height": 100,
        "name": 1
    }, {
        "originY": "top",
        "left": 0,
        "top": 0,
        "width": 118.33,
        "height": 100,
        "name": 2
    }],
    "background": ""
}

I need to loop to this string and retrieve the values of left, top, width and height and multiply them by a factor and then save them as a new string again.

Any idea of how I could accomplish this?

¿Fue útil?

Solución

Because the string is JSON, the easiest way to handle the data is to parse it into an array of objects, update the values, then output it as a string again.

// Parse
var container = JSON.parse(yourString);

// Get and update
var i, len, top, left, width, height;
len = container.objects.length;
for (i = 0; i < len; i++) {
    top = container.objects[i].top;
    left = container.objects[i].left;
    height= container.objects[i].height;
    width = container.objects[i].width;
    // * Save top, left, width somewhere. *
    // Multiply by some factor.
    container.objects[i].top *= factor;
    container.objects[i].left *= factor;
    container.objects[i].height *= factor;
    container.objects[i].width *= factor;
}

// Convert to string again.
theString = JSON.stringify(container);

Otros consejos

You can assign the json to a variable and then iterate it and do what ever you want

        var koko = {
            "objects": [{
                "originY": "top",
                "left": 1,
                "top": 0,
                "width": 118.33,
                "height": 100,
                "name": 1
            }, {
                "originY": "top",
                "left": 2,
                "top": 0,
                "width": 118.33,
                "height": 100,
                "name": 2
            }],
            "background": ""
        }



        for(var i=0;i<koko.objects.length;i++) { koko.objects[i].left = 10; }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top