I have an array of objects:
Object = {
1 : { name : bob , dinner : pizza },
2 : { name : john , dinner : sushi },
3 : { name : larry, dinner : hummus
You can find the object in array with Alasql library:
var data = [ { name : "bob" , dinner : "pizza" }, { name : "john" , dinner : "sushi" },
{ name : "larry", dinner : "hummus" } ];
var res = alasql('SELECT * FROM ? WHERE dinner="sushi"',[data]);
Try this example in jsFiddle.
If You want to find a specific object via search function just try something like this:
function findArray(value){
let countLayer = dataLayer.length;
for(var x = 0 ; x < countLayer ; x++){
if(dataLayer[x].user){
let newArr = dataLayer[x].user;
let data = newArr[value];
return data;
}
}
return null;
}
findArray("id");
This is an example object:
layerObj = {
0: { gtm.start :1232542, event: "gtm.js"},
1: { event: "gtm.dom", gtm.uniqueEventId: 52},
2: { visitor id: "abcdef2345"},
3: { user: { id: "29857239", verified: "Null", user_profile: "Personal", billing_subscription: "True", partners_user: "adobe"}
}
Code will iterate and find the "user" array and will search for the object You seek inside.
My problem was when the array index changed every window refresh and it was either in 3rd or second array, but it does not matter.
Worked like a charm for Me!
In Your example it is a bit shorter:
function findArray(value){
let countLayer = Object.length;
for(var x = 0 ; x < countLayer ; x++){
if(Object[x].dinner === value){
return Object[x];
}
}
return null;
}
findArray('sushi');
jQuery has a built-in method jQuery.grep that works similarly to the ES5 filter
function from @adamse's Answer and should work fine on older browsers.
Using adamse's example:
var peoples = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
you can do the following
jQuery.grep(peoples, function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
var getKeyByDinner = function(obj, dinner) {
var returnKey = -1;
$.each(obj, function(key, info) {
if (info.dinner == dinner) {
returnKey = key;
return false;
};
});
return returnKey;
}
jsFiddle.
So long as -1
isn't ever a valid key.