E
E
enchikiben2014-01-30 19:14:15
JavaScript
enchikiben, 2014-01-30 19:14:15

How to write an algorithm for finding a parent in an object?

Please help me write an algorithm for finding a parent in a multidimensional array in JS. There is such an array of questions, you need to find its parent question by the title of the question.

var mass = {
                "poll" : {
                    "title" : "Вопрос 1",
                    "reply" : [
                        {
                            "title":"Ответ 1.1",
                            "type":"radio",
                            "poll" : {
                                "title" : "Вопрос 2",
                                "reply" : [
                                    {
                                        "title" : "Ответ 2.1",
                                        "type" : "radio",
                                        "poll": {
                                            "title" : "Вопрос 3",
                                            "reply" : [
                                                {
                                                    "type" : "select",
                                                    "items" : []
                                                    }
                                                }
                                            ]
                                        }
                                    },
                                    {
                                        "title": "Ответ 2.2",
                                        "type":"radio"
                                    }
                                ]
                            }
                        },
                        {
                            "title": "Ответ 1.2",
                            "type":"radio"
                        }
                    ]
                }
            }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Keith, 2014-01-30
@EnChikiben

function find(title, poll, parent){
    
    parent = parent || poll;
    
    if (poll.title === title)
        return parent;
    
    var result;
    
    poll.reply && poll.reply.some(function(reply){
        return reply.poll && (result = find(title, reply.poll, poll)) || false;
    });
        
    return result;
}

find('Вопрос 2', mass.poll);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question