创建动态多维对象/数组 [英] creating dynamically multidimensional object / array

查看:64
本文介绍了创建动态多维对象/数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JS创建一个多维数组,以便我可以通过对PHP的Ajax调用发布一些数据。它可能非常简单,但我对JS的知识对于这个具体的事情很少...



这是一个带代码的JSFiddle



我想要的是某种类似的数组:

  var data = {
bewaarnaam:'bewaarnaam!',
行:[{
row_1:[{
name:'行名称1',
x:450,
y:250,
chest1:[{
counter:1,
height:5
}],
chest2:[{
counter:2,
height:3
}]
}],
row_2:[{
name:'行名称2',
x:650,
y:550,
chest1:[{
counter:1,
height:8
}],
chest2:[{
counter:2,
身高:4
}]
}],
}]
};

我正在尝试用这段代码生成对象数组:

  function saveThis(){
var bewaarNaam = $(#bewaarplaatsName)。val();
hide_overlay_save_name();
log(现在用名字来保存所有东西:+ bewaarNaam);

var dataRows = [{
'bewaarnaam':bewaarNaam
}];
$(。rows)。each(function(i,obj){
var row = $(obj);
var rowName = $(row).attr('name' );
var chests = [];

$(。cv_chest,row).each(function(i2,obj2){
chests [$(obj2)。 attr('id')] = [{
'计数器':$(obj2).attr('chest_counter'),
'height':$(obj2).attr('chest_height')
}];
});

var rowData = [{
rowName:[{
'name':$(row).attr(' name'),
'x':$(row).css('left'),
'y':$(row).css('top'),
'箱子':chests
}]
}];

dataRows [$(row).attr('id')] = rowData;
});

log(dataRows);
log(用ajax发送数据......);

$ .ajax({
类型:'post',
cache:false,
url:'{{url('
bewaarplaatsen / nieuw ')}}',
data:dataRows
})。done(function(msg){
log(ajax success);
log(msg);
})。失败(函数(msg){
log(ajax错误);
log(msg);
});
}

当我输出变量 dataRows 到控制台,我得到以下输出:

  [Object,row_1:Array [1],row_2:Array [1]] 
0:对象
bewaarnaam:Bewaar Naam!
__proto__:Object
length:1
row_1:Array [1]
0:Object
rowName:Array [1]
0:Object
chests:Array [0]
chest_1_1:Array [1]
0:Object
counter:1
height:1
__proto__:Object
长度:1

依此类推......
如果我登录变量与 console.log(JSON.stringify(dataRows)); 我得到以下输出:

  [{
bewaarnaam:Bewaar Naam!
}]

如果我执行 var data =。 .. 控制台内的部分(第一个代码块),并将数据记录到控制台,我得到以下输出(我使用`JSON.stringify函数再次记录它以获得更好的可读性):

  {
bewaarnaam:Bewaar Naam!,
行:[{
row_1:[{
name:Row Name 1,
x:450,
y:250,
chest1: [{
counter:1,
height:5
}],
chest2:[{
counter:2,
身高:3
}]
}],
row_2:[{
name:行名2,
x :650,
y:550,
chest1:[{
counter:1,
height:8
}],
chest2: [{
柜台:2,
身高:4
}]
}]
}]
}

如果我 print_r POST PHP中的值,我得到以下输出:

 数组

[undefined] ] =>

当我用Chrome调试Ajax请求时,我可以看到表格数据得到2 undefineds

 表格数据
undefined:
undefined:

所以如果我理解正确,是对象没有正确创建,因此,它没有与Ajax正确发送。因此,PHP无法对发布数据做任何事情......



所以我的问题很简单......我做错了什么/怎么做我解决了这个问题?

解决方案

您正在混合数组和对象。在javascript中,如果您使用 {key:value} ,则需要一个对象而不是一个数组。如果你想要 [value,value,value] ,那就是一个数组。当你说 x = [{}] 你实际上在数组中创建了一个对象,但是你要在数组上设置属性(数组也是对象),而不是正确的对象。



你最想要的是在任何地方使用对象并摆脱所有数组:



http://jsfiddle.net/k5Q3p/1/

  var dataRows = {
'bewaarnaam':bewaarNaam,
rows:{}
};

$(。rows)。each(function(i,obj){
var row = $(obj);
var rowName = $(row).attr ('name');
var chests = {};

$(。cv_chest,row).each(function(i2,obj2){
log(另一个带有id的箱子:+ $(obj2).attr('id'));
箱子[$(obj2).attr('id')] = {
'柜台':$( obj2)。attr('chest_counter'),
'height':$(obj2).attr('chest_height')
};
});

var rowData = {
rowName:{
'name':$(row).attr('name'),
'x':$(row).css('left') ,
'y':$(行).css('top'),
'箱子':箱子
}
};

dataRows .rows [$(row).attr('id')] = rowData;
});

创建类似



<$ p $的结构p> {
bewaarnaam:Bewaar Naam!,
rows:{
row_1:{
rowName:{
name:Rij 1,
x:30px,
y:120px,
箱子:{
chest_1_1:{
counter:1,
height:3
},
chest_1_2:{
counter :2,
身高:3
},
chest_1_3:{
柜台:3,
身高 :3
},
chest_1_4:{
counter:4,
height:3
},
chest_1_5:{
counter:5,
height:3
}
}
}
} ,
row_2:{
rowName:{
name:Rij 2,
x:30px,
y:200px,
箱子:{
chest_2_1:{
柜台:1,
身高: 6
},
chest_2_2:{
柜台:2,
身高:6
},
chest_2_3:{
counter:3,
height:6
},
chest_2_4:{
counter :4,
身高:6
}
}
}
}
}
}


I'm trying to create an multidimensional array with JS so that i can post some data with an Ajax call to PHP. It's probably very simple, but my knowledge of JS is very little regarding this specific thing...

Here's an JSFiddle with the code

what i want is some kind of array like this:

var data = {
    bewaarnaam: 'bewaarnaam!',
    rows: [{
        row_1: [{
            name: 'Row Name 1',
            x: 450,
            y: 250,
            chest1: [{
                counter: 1,
                height: 5
            }],
            chest2: [{
                counter: 2,
                height: 3
            }]
        }],
        row_2: [{
            name: 'Row Name 2',
            x: 650,
            y: 550,
            chest1: [{
                counter: 1,
                height: 8
            }],
            chest2: [{
                counter: 2,
                height: 4
            }]
        }],
    }]
};

I'm trying to generate the object array with this piece of code:

function saveThis() {
    var bewaarNaam = $("#bewaarplaatsName").val();
    hide_overlay_save_name();
    log("now where going to save everything with the name: " + bewaarNaam);

    var dataRows = [{
        'bewaarnaam': bewaarNaam
    }];
    $(".rows").each(function (i, obj) {
        var row = $(obj);
        var rowName = $(row).attr('name');
        var chests = [];

        $(".cv_chest", row).each(function (i2, obj2) {
            chests[$(obj2).attr('id')] = [{
                'counter': $(obj2).attr('chest_counter'),
                    'height': $(obj2).attr('chest_height')
            }];
        });

        var rowData = [{
            rowName: [{
                'name': $(row).attr('name'),
                    'x': $(row).css('left'),
                    'y': $(row).css('top'),
                    'chests': chests
            }]
        }];

        dataRows[$(row).attr('id')] = rowData;
    });

    log(dataRows);
    log("sending data with ajax...");

    $.ajax({
        type: 'post',
        cache: false,
        url: '{{ url('
        bewaarplaatsen / nieuw ') }}',
        data: dataRows
    }).done(function (msg) {
        log("ajax success");
        log(msg);
    }).fail(function (msg) {
        log("ajax error");
        log(msg);
    });
}

When i output the variable dataRows to the console, i get the following output:

[Object, row_1: Array[1], row_2: Array[1]]
    0: Object
        bewaarnaam: "Bewaar Naam!"
    __proto__: Object
    length: 1
    row_1: Array[1]
        0: Object
            rowName: Array[1]
                0: Object
                    chests: Array[0]
                        chest_1_1: Array[1]
                            0: Object
                                counter: "1"
                                height: "1"
                                __proto__: Object
                                length: 1

And so on... If I log the variable with console.log(JSON.stringify(dataRows)); I get the following output:

[{
    "bewaarnaam": "Bewaar Naam!"
}]

While if i execute the var data =... part ( first code block ) inside the console, and log the data to the console, i get the following output (i logged it again with the `JSON.stringify function for better readability):

{
    "bewaarnaam": "Bewaar Naam!",
    "rows": [{
        "row_1": [{
            "name": "Row Name 1",
            "x": 450,
            "y": 250,
            "chest1": [{
                "counter": 1,
                "height": 5
            }],
            "chest2": [{
                "counter": 2,
                "height": 3
            }]
        }],
        "row_2": [{
            "name": "Row Name 2",
            "x": 650,
            "y": 550,
            "chest1": [{
                "counter": 1,
                "height": 8
            }],
            "chest2": [{
                "counter": 2,
                "height": 4
            }]
        }]
    }]
}

If I print_r the POST value in PHP, i get the following output:

Array
(
    [undefined] => 
)

When i debug the Ajax request with Chrome, i can see that the Form Data got 2 undefineds:

Form data
undefined:
undefined:

So if I understand it right, is the object not created properly, and therefore, it isn't properly send with Ajax. And because of that, PHP can't do anything with the post data...

So my question is pretty simple... What am i doing wrong / how do i fix this problem?

解决方案

You're mixing arrays and objects. In javascript, if you're using {key:value}, you want an object rather than an array. If you want [value,value,value] it's an array. When you say x=[{}] you're actually creating an object inside an array, but then you're setting properties on the array (arrays are objects too), rather than in the correct object.

What you most likely want is to just use objects everywhere and get rid of all the arrays:

http://jsfiddle.net/k5Q3p/1/

var dataRows = {
    'bewaarnaam': bewaarNaam,
    rows:{}
};

$(".rows").each(function (i, obj) {
    var row = $(obj);
    var rowName = $(row).attr('name');
    var chests = {};

    $(".cv_chest", row).each(function (i2, obj2) {
        log("another chest with id: " + $(obj2).attr('id'));
        chests[$(obj2).attr('id')] = {
            'counter': $(obj2).attr('chest_counter'),
                'height': $(obj2).attr('chest_height')
        };
    });

    var rowData = {
        rowName: {
            'name': $(row).attr('name'),
                'x': $(row).css('left'),
                'y': $(row).css('top'),
                'chests': chests
        }
    };

    dataRows.rows[$(row).attr('id')] = rowData;
});

which creates a structure like

{
  "bewaarnaam": "Bewaar Naam!",
  "rows": {
    "row_1": {
      "rowName": {
        "name": "Rij 1",
        "x": "30px",
        "y": "120px",
        "chests": {
          "chest_1_1": {
            "counter": "1",
            "height": "3"
          },
          "chest_1_2": {
            "counter": "2",
            "height": "3"
          },
          "chest_1_3": {
            "counter": "3",
            "height": "3"
          },
          "chest_1_4": {
            "counter": "4",
            "height": "3"
          },
          "chest_1_5": {
            "counter": "5",
            "height": "3"
          }
        }
      }
    },
    "row_2": {
      "rowName": {
        "name": "Rij 2",
        "x": "30px",
        "y": "200px",
        "chests": {
          "chest_2_1": {
            "counter": "1",
            "height": "6"
          },
          "chest_2_2": {
            "counter": "2",
            "height": "6"
          },
          "chest_2_3": {
            "counter": "3",
            "height": "6"
          },
          "chest_2_4": {
            "counter": "4",
            "height": "6"
          }
        }
      }
    }
  }
}

这篇关于创建动态多维对象/数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆