开发者

Extracting multiple object values

I have an object like this:

object["key1"] = "text1"
object["key2"] = "text2"
object["key3"] = "text1"
object["key4"] = "text3"

How can I give out (e.g. alert) the elements with the same values (text1, text2 and so on)?

In the above example it should be object[开发者_开发技巧"key1"] and object["key2"].

Thanks


You could "invert" your object (properties become values, values become properties):

var byValue = {};

for (var prop in object) {
    if (!(object[prop] in byValue)) {
        byValue[object[prop]] = [];
    }
    byValue[object[prop]].push(prop);
}

This should yield this structure:

{
    'text1': ['key1', 'key3'],
    'text2': ['key2'],
    'text3': ['key4']
}

Then, you can detect those values that had duplicate keys:

for (var value in byValue) {
    if (byValue[value].length > 1) {
        alert(byValue[value].join(', '));
    }
}


I have sorted the array and then considered that you would want to alert,or do any functionality, only once for every repeated element. WARNING: Sorting can get heavy with the size of the array http://jsfiddle.net/SPQJ7/ The above fiddle is already setup and working with multiple reapeated elements


I updated my script

http://jsfiddle.net/HerrSerker/LAnRt/

This does not check for identity in complex values, just for equality (see foo example)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜