indexedObject + itemOf
by sanford
JavaScript
function indexedObj(o) {
for (var prop in o) {
if (o.hasOwnProperty(prop))
this[prop] = o[prop];
}
}
indexedObj.prototype.valueOf = function() {
return this['@idx'];
};
var sampleDeep = {
elements: [
new indexedObj({
'@idx': 20,
title: 50
}), new indexedObj({
'@idx': 999,
desc: 40
}), new indexedObj({
'@idx': 2000,
elements: [
new indexedObj({
'@idx': 101
})
]
})
]
}
var NaV = 'undefined';
// indexOf that can switch between loose (default) and strict equality
Array.prototype.itemOf = function(search, strict) {
var strict = typeof strict !== NaV ? strict : true,
foundIndex = -1;
if (strict) {
foundIndex = Array.prototype.indexOf.call(this, search);
} else {
this.forEach(function(itm, idx) {
if (itm == search && foundIndex == -1) {
foundIndex = idx;
}
});
}
return {
index: foundIndex,
item: this[foundIndex]
}
}
console.log(sampleDeep.elements.itemOf(2000, false).item.elements.itemOf(101, false));
console.log(JSON.stringify(sampleDeep, function(k, v) {
if (k !== '@idx') return v;
}))