JSFiddle - React, Tailwind, and code Playground
by Graham Dixon
JavaScript
var array = [{
name: 'One',
// index??
data: {
title: 'Title One',
content: 'Content One'
}},
{
name: 'Two',
data: {
title: 'Title Two',
content: 'Content Two',
html: [{ name: 'four',
data: {
title: 'Title Threee',
content: 'Content Three'
} }]
}},
{
name: 'Three',
data: {
title: 'Title Three',
content: 'Content Three'
}}];
function findByName(array, name, index) {
//recursive by providing blank index once;
if(typeof index === 'undefined'){
index = [];
}
$(array).each(function(i, e) {
if (e.name && e.name == name) {
found = true;
index.push(i);
return false;
}else{
if(typeof e.data.html === "object"){
index.push(i);
findByName(e.data.html, name, index);
}
}
});
if(typeof found !== 'undefined'){
return index;
}else{
return -1;
}
}
console.clear()
console.log(findByName(array, "four")); // prints [1,0]
// and now even better ... find by any property
function findByProperty(objects, prop, value) {
var index;
$(objects).each(function(i, e) {
if (e[prop] && e[prop] == value) {
index = i;
return false;
}
});
return index;
}
// usage
//var index = findByProperty(array, "name", "One");
//console.log(index); // prints 0
//index = findByProperty(array, "name", "Three");
//console.log(index); // prints 2
// and even more powerful
function findByFilter(objects, filter) {
var index;
$(objects).each(function(i, e) {
if (filter(i, e)) {
index = i;
return false;
}
});
return index;
}
index = findByFilter(array,function(i,e){ return e.data.title=="Title Threee"; });
//console.log(index);
//console.log(array[index]);