简体   繁体   中英

How to turn JavaScript array of objects into jQuery prependTo

In the following exampmle I'm setting an array of objects and sort them by a key parameter (position). I then need to output the result - but how? See the comment in the code.

$(document).ready(function () {

    function sortHooks(){

        // add modules
        var modules = [ 
            { module: 'navbar', hook: 'hook-header', position: '2'},
            { module: 'logo', hook: 'hook-header', position: '3'},
            { module: 'description', hook: 'hook-header', position: '1'}
        ];

        // sort by "position" ASC
        function byPosition(a,b) {
            if (a.position < b.position)
                return -1;
            if (a.position > b.position)
                return 1;
            return 0;
        }

        // jQuery function with the given parameters
        /*  for each modules as modules
            for each hook as hook
            do the following:
            $( '#' + module )prependTo( '#' + hook )

            so for the given example it should return
            $('#description')prependTo('hook-header')
            $('#navbar')prependTo('hook-header')
            $('#logo')prependTo('hook-header')

            so they can be executed in that specific order.
            And since we're using "prepend" that will mean
            that the items be placed like this:
            #logo
            #navbar
            #description
        */

        return ???
    }

    // Execute sortHooks function
    sortHooks();
});

Maybe something like this, but I'm not exactly sure:

$.each(modules, function(index, value) {
    $( '#' + value.module ).prependTo( '#' + value.hook ));
});

I've tried a bunch of other things as well, one of them being Hook elements with insertAfter, but stay in parent - jQuery , which worked perfectly, but if the position was higher than the children inside the parent it didn't know what to do with it and causing a lot of unwanted behavior.

function byPosition(a,b) { return a.position-b.position; }
modules.sort(byPosition);
modules.forEach(function(obj){
    $('#'+obj.madule).prependTo('#'+obj.hook);
});

just use a regular loop

for(var i=0; i<modules.length; i++){
   $( '#' + modules[i].module )prependTo( '#' + modules[i].hook );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM