0

我有一个对象,其中包含 2 个名称参数 - 请参见下面的示例。我知道要到达我需要遍历对象的数据,但我觉得这太烦人了。有没有更好的方法以简单的方式获取数据?

var obj = {[[[{name:'one'},{name:'two'}]]]};

$.each(obj,function(i,val){
    var first = [] // i will get first time
    $.each(first, function(i, val){
        var second = [] //i will get second time and third later fourth  // like so?
    })
})

这是否意味着我应该循环该each函数四次以获取name值?如果是这样,哪种方法是正确的?有没有办法使用相同的函数来获取数据?

4

3 回答 3

1

obj的无效。

所以,试试这个:

var obj = [[[{
        name: 'one'},
    {
        name: 'two'}]]];

$.each(obj[0][0], function() {
  alert( this.name );
});

演示


另一个(适用于任何级别的数组)

var obj = [[[{
    name: 'one'},
{
    name: 'two'}]]];

function getObject(obj) {
    if (Object.prototype.toString.call(obj[0]) == '[object Array]') {
        getObject(obj[0]);
    } else {
        $.each(obj, function() {
            alert(this.name);
        });
    }
}

getObject(obj);​

演示


笔记

{}始终包含key : value配对数据。因此,在您的情况下{ [ .. ] }是无效的对象格式。一些正确的对象格式可能是:

{ key1: value1, key2: value2, .. }

{ data: [{key1: value1}, {key2: value2}] }

建议

If you've option then change the format of your obj like below:

var obj = [
   { name: 'one' },
   { name: 'two' }
];

And try following code simply:

$.each(obj, function() {
  alert( this.name );
});
于 2012-08-14T10:44:07.747 回答
1

You should search with a recursive function. You can through your object with n tables.

var obj = [[[[{name:'one'},{name:'two'}]]]];

function troughTables(table){
    if(table instanceof Array && table.length == 1){
        troughTables(table[0]);
        return;
    }

    console.log("here is a content table");
}

troughTables(obj)

With this you can have much tables but the condition is the length must be 1.

于 2012-08-14T10:46:11.080 回答
0

You can serialize this object to JSON and get data with regexp.

Also you can use to flatten arrays:

jQuery.map(obj, function(n){return n})

And you will get result like:

[{name:'one'},{name:'two'}]
于 2012-08-14T10:58:45.267 回答