Tips for creating a function that outputs an array containing all the values within an object

Any help to get me through an assignment I am currently stuck on would be greatly appreciated. I am aware that the title of this post might seem confusing, so I will do my best to elaborate. Here is the assignment in question:

The task is to create a function named getValues. This function should: take one parameter, an object return an array containing all the values within the object. Additionally, it should return an empty array if no values are present.

The function should display the values of {name: "Rob", age: 25}

I managed to write the function successfully. Here it is:

var name = ("Rob");
var age = (25);

var getValues = function() {
return [name, age];
};

The issue arises when I attempt to write a function returning an empty array, as it interferes with the prior function.

Is there a way to modify this code so that both functions can coexist successfully? Can this function be altered to perform both tasks effectively? I am new to programming and any guidance would be greatly appreciated.

Answer №1

In this scenario, there is no need for a distinct function to manage the scenario of an empty array. Instead, a single function called getValues is utilized, incorporating an if-else statement to handle both situations.

JavaScript includes a built-in mechanism for extracting values from an object.

function getValues(obj) {
  return Object.values(obj);
}

It is important to consider the scenario where the object is undefined in order to prevent any errors in the code. Rather than creating a separate function with the same name, an if statement is used to address the undefined scenario.

function getValues(obj) {
  if (!obj) {
    return [];
  }

  return Object.values(obj);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bidirectional linking using URL query parameters and form inputs (select boxes and sliders)

Presently, I am able to retrieve the GET parameters using $location.$$search. Nevertheless, I am still unsure about how to implement 2-way binding for both the URL and FORM in the following scenario. In the demo image below, when a user updates the FORM ...

jQuery Issue - Clash between multiple menus sharing the same class

Hey there! I'm currently diving into the world of jQuery and encountering an issue with my menu. Whenever I click on a menu item with either the "tm-nav-vertical" or "tm-nav-horizontal" class, it removes the .active class from the initial menu item. I ...

Issue with event.stopPropagation() in Angular 6 directive when using a template-driven form that already takes event.data

I am currently developing a citizenNumber component for use in forms. This component implements ControlValueAccessor to work with ngModel. export class CitizenNumberComponent implements ControlValueAccessor { private _value: string; @Input() place ...

What are some recommended methods in Angular for developing reusable panels with both controller and view templates?

I am still getting acquainted with angularjs, so there might be something I'm overlooking, but I'm struggling to find an efficient way to create reusable views that can be instantiated within a parent view. My specific scenario involves a web ap ...

Titanium: Warning upon initiation

Is it feasible to trigger an alert immediately after a window finishes loading? I am using a create window function followed by an alert message, then returning. function NewView() { var self = Ti.UI.createWindow({}); alert("A basic or confirm al ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

Unable to host Express app on Firebase functions emulator due to a port conflict with error code EADDRINUSE: address already in use :::3000

Testing the deployment of an express app on Firebase using Firebase functions has presented a challenge for me. Upon running the command firebase serve, I encountered the error EADDRINUSE: address already in use :::3000. Below is my index.js file: const fu ...

What is the best way to transfer data between functions prior to serializing and submitting the form?

Here are two functions I am working with: $("#form_pdetail").on("click", "#register_button", function() { var detail_add = $("#form_pdetail").serialize(); var request = $.ajax({ type: 'POST', url: "{{ path('product_d ...

The CSS style of the Div element is not being displayed properly when embedded with JavaScript

Currently, I am working on a simple page for practice purposes. The main issue I am facing is with a div element that has a red border and a blue background. Inside the div, there is a script tag calling an external JavaScript file. Surprisingly, the JavaS ...

Looping through a jQuery/js script, adding a unique variable with varying ending numbers to individual div elements

Imagine having an array of variables like so: example1 = 1 example2 = 32 example3 = 3345 and so forth up to something large, for instance example100 = 222 The goal is to insert each number into a separate div, with each div identified by: <div class ...

Is it necessary to encapsulate Factory calls within a function in my Controller file?

Typically, I call a Factory from my Angular controller directly within the controller function without creating a separate method. For instance: (function () { 'use strict'; angular.module("Dashboard") .controller("DashboardController", D ...

What causes the elements in my JSON file to load in a seemingly random order when clicked on?

Scenario in a simplified test case: I created a slider with 2 slides, each containing a 'video' link. When the link is clicked, a <div> is displayed with an array of objects (images). Issue at hand: Upon clicking the 'video' link ...

Eliminating attributes in mapStateToProps

When wrapping material TextField with a redux component, it is important to consider that some properties should be used in mapStateToProps only and not passed directly to the component. Otherwise, an Unknown prop warning may occur. Even specifying an unde ...

If statement utilized for conditional looping

As I dive into the world of basic JavaScript, I'm eager to understand how to loop back to the beginning of a method under specific conditions. Consider this scenario: in order for the program to progress to the statement "The character you typed was, ...

The JavaScript object is unable to reach the PHP controller

When I attempt to send a JavaScript Object to my PHP controller, it is arriving empty. Here is the object: https://i.sstatic.net/19gFV.png Upon arrival, the object appears empty. Here is my AJAX code: https://i.sstatic.net/ekHsC.png var SendMovs = { ...

Is it possible to include a while loop for iteration inside a AJAX success function?

I'm currently working on dynamically creating an accordion and populating the content of each tab using AJAX. In my main HTML page, there is an empty div reserved for the accordion: <div id="accordion"></div> The desired outcome is to ha ...

Is it possible to execute a controller function only when the textarea has completely loaded?

My current setup includes a textarea as shown below: <textarea rows="3" maxlength="144" ng-maxlength="144" type="text" name="testPost" id="testPost_{{item.id}}" ng-init="focusText('testPost', item.id)" ng-model=" ...

AngularJS: Monitoring $locationChangeStart for token verification

I am attempting to check if the next has a token or not, but it is not working and I am getting an error: TypeError: Cannot read property 'next' of undefined Any suggestions? app.js .run(function ($rootScope, $location,$log,User) { ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Utilizing Promise.all with map and async functions in Node.js ensures non-blocking behavior during function calls

After developing a small module to communicate with Zookeeper and retrieve a list of service endpoints, everything seems to be working smoothly except for the part where the list of endpoints is returned. Within the module, there is a function that is supp ...