Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

recursion - How do I recursively search an object tree and return the matching object based on a key/value using JavaScript/Prototype 1.7

I've got some nested object data and I want to search it and return the matching object based on the id.

var data = [{id: 0, name: 'Template 0', subComponents:[
        {id: 1, name: 'Template 1', subItems:[
            {id: 2, name: 'Template 2', subComponents:[{id: 3, name: 'Template 3'}], subItems: [{id: 4, name: 'Template 4'}]}
        ]}
    ]}
];

So I want to do something like this

getObjectByKeyValue({id: 3}) 

and have it return

{id: 3, name: 'Template 3'}

It's sort of got to be done generically because I have subItems, AND subComponents which could each have children.

I tried this using Prototype 1.7 and no luck - I think this just searches an array, and not a tree with it's sub nodes:

data.find(function(s){return s.id == 4;})

Thanks in advance!!!!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I went a slightly different route and made the findKey method an Object protype:

Object.prototype.findKey = function(keyObj) {
    var p, key, val, tRet;
    for (p in keyObj) {
        if (keyObj.hasOwnProperty(p)) {
            key = p;
            val = keyObj[p];
        }
    }

    for (p in this) {
        if (p == key) {
            if (this[p] == val) {
                return this;
            }
        } else if (this[p] instanceof Object) {
            if (this.hasOwnProperty(p)) {
                tRet = this[p].findKey(keyObj);
                if (tRet) { return tRet; }
            }
        }
    }

    return false;
};

Which you would call directly on the data object, passing in the key/value you're looking for:

data.findKey({ id: 3 });

Note that this function allows you to find an object based on any key:

data.findKey({ name: 'Template 0' });

See example → (open console to view result)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...