score:3

Accepted answer

You could use a special treatment for concatination the path.

function getPath(object, search) {
    function iter(o, p) {
        return Object.keys(o).some(function (k) {
            if (k === key && o[k] && o[k].type === value) {
                path = p.concat(k).join('.');
                return true;
            }
            if (o[k] !== null && typeof o[k] === 'object') {
                return iter(o[k],
                    k === 'properties' && !o.title ?
                        p :
                        p.concat(k === 'properties' && o.title ? o.title : k)
                );
            }
        });
    }

    var parts = search.split(':'),
        key = parts[0],
        value = parts[1],
        path;

    iter(object, []);
    return path;
}

var data = { title: "person", type: "object", properties: { "first name": { type: "string" }, "last name": { type: "string" }, age: { type: "number" }, birthday: { type: "string", format: "date-time" }, address: { type: "object", properties: { "street address": { type: "object", properties: { "house number": { type: "number" }, lane: { type: "string" } } }, city: { type: "string" }, state: { type: "string" }, country: { type: "string" } } }, "phone number": { type: "array", items: { type: "object", properties: { location: { type: "string" }, code: { type: "number" } }, required: ["location", "code"] } }, children: { type: "array", items: { type: "string" } }, nickname: { type: "string" } } };

console.log(getPath(data, 'country:string'));
.as-console-wrapper { max-height: 100% !important; top: 0; }


Related Query

More Query from same tag