Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question