문제

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?

도움이 되었습니까?

해결책

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);

다른 팁

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; }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top