繁体   English   中英

遍历键值为数组的对象(其值为对象)

[英]Loop through object whose key's values are arrays (the values of which are objects)

不幸的是,我的问题昨天已关闭-我通读了他的回答,但我仍然陷入困境。 我已经学到了更多有关它的信息,但似乎无法正确解决。 我正在发生一些疯狂的多维疯狂,这使我感到困惑!

fresh_posts.php:

{ 
    "posts":{
        "5": {
            "id":"5",
            "image":"link.jpg",
            "submitter":"4322309",
            "views":"3"
        },
        "2": {
            "id":"2",
            "image":"link.jpg",
            "submitter":"4322309",
            "views":"5"
        }
    },

    "comments":{
        "2": [{
            "id":"1",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"2"
        },
        {
            "id":"2",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"2"
        }
    ],
        "5": [{
            "id":"3",
            "submitter":"submitter",
            "time":"2435657",
            "comment":"comment",
            "score":"10",
            "postid":"5"
        }]
    }
}

最初,我会:

$.getJSON('fresh_posts.php',function(data){
    global_save_json = data.comments; // saves comments object for later use
    ... 
})

然后,我稍后在click函数中使用它(在getJSON之外)。

$('.main').on('click','.new-comments',function(e){

    var fullid = e.target.id;
    var subid = fullid.substring(8); // subid = the number of string e.g. "show-all88" from fullid becomes "88" from subid.

    function appendAllComments(input){

        $.each(global_save_json.input,function(index,value){
            for (var key in value) {
                if (value.hasOwnProperty(key)) {
                    console.log(key + " -> " + value[key]);
                }
            }
        })

    }

    appendAllComments(subid);

})

•假设我们虽然发送了输入2 (在上面的示例JSON对象中),但是我需要遍历该数组(该数组的每个值包含一个对象)。 所以我们做(?):

$.each(global_save_json.2,function(index,value){

还是

$.each(global_save_json."2",function(index,value){

^我们正在遍历数组中的每个值(?)

•然后,对于每个对象(每个数组的值都是对象):

for (var key in value) {
    if (value.hasOwnProperty(key)) {
        console.log(key + " -> " + value[key]);
    }
}

从上面的$.each()循环中,我们将数组值定义为“ value”,所以现在当我们循环对象“ value”时,对吗?

所有这些似乎都不起作用,或者一直抛出错误(当前cannot read property 'length' of undefined ),因此,感谢您的帮助。

好吧,很高兴您能弄清楚,这是我的官方答复:

obj.key语法与obj['key']等效,如果您要索引的键是文字键,则它很有用。 但是,当您要以编程方式查找键时,则可以使用后一种语法,因为您可以执行var input = 2; obj[input] var input = 2; obj[input] (在JavaScript中,所有键都是字符串,因此无论input = 2还是input = '2'都没有关系,当运行时看到obj[input] ,它将强制input为字符串。)无法使用带有存储键名的变量的点语法。

综上所述,您永远不能将数字值用作点语法的键。 对于具有数字键的数组和对象(从技术上讲,JS数组是对象,因此这种区别是超精细的……),您永远无法执行obj.2arr.0 ,而使用括号语法: obj[2]arr[0]

提示:在尝试弄清楚如何将这种深层嵌套的对象切片和切块时,使用JavaScript控制台真的很有帮助。 您可以在文章顶部复制JSON数据, 打开JS控制台 ,输入var data = <PASTE> 这是可行的,因为JSON代表“ JavaScript对象表示法”并且是有效的JavaScript! 然后,您可以输入data.comments.2并看到它是一个语法错误,与data.comments.'2'类似。 但是data.comments[2]提供了两个对象,因此您可以运行data.comments[2].map(function(val, idx) {return val.comment})来确保获得语法。

(如果你做了很多与JS对象和数组和数据,我建议lodash或类似的项目,如Ramda特里尼 。)

你需要经过两次

for (var key in obj) {
    //Get posts and comments
    var objectsInner = obj[key];

    for (var key2 in objectsInner) {
        //This is arrays in posts and comments
        // key2 has values '2' and '5', and inside these objects you have an array
        var arrays = objectsInner[key2];
    }
}

并且您可以创建一个函数来基于输入('2')检索所有数据,请看一下这个小提琴http://jsfiddle.net/Ldk9spne/

像这样:

var posts = data.posts;
var comments = data.comments;

// Cycle for posts
for(var id in posts) {
    // Get comments for post
    if (comments[id] !== undefined) {
        comments[id].forEach(function(c){
            console.log('Comment '+ c.id +' for post ' + id +', made by '+ c.submitter +': ' + c.comment);
        });
    }
}

示例: http//jsbin.com/pacuqetita/1/edit?js,console

为什么您不能区别对待帖子和评论,因为两者的数据不同。 请尝试这样的事情

 $.each(data,function(key, postsOrComments){ if (key == 'posts') { $.each(postsOrComments, function(index, post) { console.log(post); }); } else if (key == 'comments') { $.each(postsOrComments, function(index, comments) { $.each(comments, function(index, comment) { console.log(comment); }); }); } });`` 

数据变量必须是您的ajax输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM