A
A
Axepec2016-02-08 19:58:35
JavaScript
Axepec, 2016-02-08 19:58:35

JS How, having the name of the parameter inside the object, find it (by looking at all nested objects) and !!! get a path to it?

Hello sir, please help!!
we have the name parameter, everything is fine, just fine!
we have an object:
object {
client: {
name: 'Vasya'
phone: '799999999'
}
order: {
param1: '2122'
param2: '1231'
}
}
How to find the path to this name?
i.e. get ------> object.client.name
if param2 parameter then accordingly object.order.param2
ps objects are large, but there are no parameter repetitions, if using for in I can't display the path....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-02-09
@Axepec

Although the question is more like "do everything for me", the problem itself seemed interesting to me, here is the solution:

function findParamPath(obj, prop) {
    if(obj.hasOwnProperty(prop)) return prop;
    var props = Object.getOwnPropertyNames(obj);
    for(var i = props.length; i--; ) {
        if(typeof obj[props[i]] !== 'object') continue;
        var path = findParamPath(obj[props[i]], prop);
        if(path) return props[i] + '.' + path;
    }
    return null;
}

we test:
var obj = {
    object : {
        client : {
            name : 'Вася',
            phone : '799999999'
        },
        order : {
            param1 : '2122',
            param2 : '1231'
        }
    }
};

console.log(findParamPath(obj, 'name')); // 'object.client.name'
console.log(findParamPath(obj, 'param1')); // 'object.order.param1'
console.log(findParamPath(obj, 'unknown')); // null (не найдено)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question