Как создать JSON объект или массив из идентификаторов Div? - PullRequest
2 голосов
/ 22 марта 2012

У меня есть ситуация, когда мне нужно создать JSON из некоторых идентификаторов на моей странице.

вот какой-то код. а также jsfiddle

<ul class="wall_message">
    <li id="167" class="msgid">
        <div class="wall_msg">text</div>
        <div id="129" class="comments">
            <div class="wall_img">commemt</div>
        </div>
        <div id="130" class="comments">
            <div class="wall_img">commemt</div>
        </div>
    </li>
    <li id="166" class="msgid">
        <div class="wall_img">text</div>
        <div class="wall_msg">
            <div id="134" class="comments">
                <div class="wall_img">commemt</div>
            </div>
            <div id="136" class="comments">
                <div class="wall_img">commemt</div>
            </div>
        </div>
    </li>
</ul>​

var jsonObj = []
var jsonObj1 = [];

$('.msgid').each(function(index,val){
    jsonObj.push({ids : $(this).attr('id')});
});

$('.comments').each(function(index,element){
    jsonObj1.push({id : $(this).attr('id')});
});

console.log(jsonObj);
console.log(jsonObj1);

это вернет 2 объекта для jsonObj и 4 для jsonObj1

Мне нужно как-то объединить их, чтобы результат был:

ids: "167"
comment: {
    id: "129"
    id: "130"
}

ids: "166"
comment: {
    id: "134"
    id: "136"
}

Я думаю, что мне нужно сделать другой foreach в первом foreach и добавить к json другие идентификаторы, однако я не уверен, как это сделать.

есть идеи?

Ответы [ 3 ]

4 голосов
/ 22 марта 2012

Более краткий вариант ответа AndreasAL:

var jsonObj = $(".msgid").map(function() {
    var obj = { id: this.id };

    obj.comments = $(".comments", this).map(function() {
        return { id: this.id };
    }).get();

    return obj;
}).get();
2 голосов
/ 22 марта 2012

Я придумал другую конструкцию json, как показано ниже,

jsonObj = [
           {'ids': '167', 'comments': ['129', '130']},
           {'ids': '166', 'comments': ['134', '136']}
];

См. Код ниже, если вы заинтересованы в приведенной выше конструкции,

DEMO

var jsonObj = [];
var len, comments;
$('.msgid').each(function(index){
    len = jsonObj.push({'ids' : $(this).attr('id')});
    comments = [];
    $(this).find('.comments').each (function () {
        comments.push($(this).attr('id'));
    });
    jsonObj[len - 1]['comments'] = comments;
});

console.log(jsonObj);
1 голос
/ 22 марта 2012
var jsonObj = [];

$('.msgid').each(function(){
    var obj = {
        id: this.id,
        comments: []
    };
    $(".comments", this).each(function() {
        obj.comments.push({
            id: this.id
        });
    });
    jsonObj.push(obj);
});

console.log(jsonObj);

это выдаст:

[
    {
        id: "167",
        comments: [
            {
                id: "129"
            },
            {
                id: "130"
            }
        ]
    },
    {
        ....
    }
]
...