Функция Underscore.js _.object()

Опубликовано: 7 Октября, 2022

Функция _.объект():

  • Он преобразует элементы массива в объекты.
  • Мы можем либо передать все ключи, а затем все значения, либо передать ключ вместе с их значением парами.
  • Он используется, если у нас есть более одного массива, но мы хотим установить/сформировать связь между этими массивами.
  • Кроме того, размер массивов не обязательно знать заранее.

Синтаксис:

_.object(list, [values])

Параметры:
Он принимает два аргумента:

  • Список
  • Ценности

Возвращаемое значение:
Он возвращает массив со списком пар из переданных ключей и значений.

Примеры:

  1. Passing 2 lists to _.object() function:
    The ._object() function takes the element from the list one by one and makes it as an object with the value given in the other list. It takes the first elements of both the arrays and make them a single object by taking first array’s elements as the key and the other array’s as value. It will work only on first 2 arrays passed even if we pass a third array.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.object(["Akash", "Amit", "Aviral"], [01, 02, 03]));
        </script>
    </body>
       
    </html>

    Output:

  2. Passing key along with it’s value in a single list to _.object() function:
    The ._object() function takes the element from the list one by one and makes it as an object with the value given along with it in the same list. It takes all the elements in the first array and then form it a single object. It treats first array passed as a single object. We can pass n number of lists in this function.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.object([["Akash", "Amit"], [01, 02], ["pass", "pass"]]));
        </script>
    </body>
       
    </html>

    Output:

  3. Using _.object() function in real life
    In this we use the second type of syntax mentioned above. If we want to obtain a database of a student named Amit (here) so we can just pass the parameters like his name, roll number and his result along with his details like his roll number is 2 and he is passed to the next class.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.object([["Name", "Amit"], ["rollNo", 02], ["pass", "yes"]]));
        </script>
    </body>
       
    </html>

    Output:

  4. Another way to obtain the same result as in example third using _.object() function:
    In this also the result obtains will be same but the method of passing the key and value is different like here we pass all the keys in one array. Then, in the other array we pass all the values. Then the first element of the first array forms the first key and the first element of the second element of the second array as the value.




    <!-- Write HTML code here -->
    <html>
       
    <head>
        <script src
        </script>
    </head>
       
    <body>
        <script type="text/javascript">
            console.log(_.object(["Name", "rollNo", "pass"], ["Amit", 02, "yes"]));
        </script>
    </body>
       
    </html>

    Output:

ПРИМЕЧАНИЕ:
Эти команды не будут работать в консоли Google или в Firefox, так как необходимо добавить эти дополнительные файлы, которых они не добавили.
Итак, добавьте указанные ссылки в свой HTML-файл, а затем запустите их.
Ссылки следующие:

Пример показан ниже: