How to find a value in an array of objects in JavaScript?

前端 未结 10 2572
情话喂你
情话喂你 2020-11-28 18:08

I have an array of objects:

Object = {
   1 : { name : bob , dinner : pizza },
   2 : { name : john , dinner : sushi },
   3 : { name : larry, dinner : hummus         


        
10条回答
  •  春和景丽
    2020-11-28 19:07

    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');
    

提交回复
热议问题