w3resource

JavaScript: Retrieve all the values of an object's properties

JavaScript Object: Exercise-14 with Solution

Retrieve Object Values

Write a JavaScript function to retrieve all the values of an object's properties.

Sample Solution:

JavaScript Code:

function all_values(obj) {
    var keys = _keys(obj);
    var length = keys.length;
    var values = Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[keys[i]];
    }
    return values;
  }
function _keys(obj) 
 {
    if (!isObject(obj)) return [];
    if (Object.keys) return Object.keys(obj);
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    return keys;
  }
function isObject(obj)   
{  
    var type = typeof obj;  
    return type === 'function' || type === 'object' && !!obj;  
  } 
console.log(all_values({red: "#FF0000", green: "#00FF00", white: "#FFFFFF"}));

Output:

["#FF0000","#00FF00","#FFFFFF"]

Flowchart:

Flowchart: JavaScript:- Retrieve all the values of an object's properties

Live Demo:

See the Pen javascript-object-exercise-14 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that returns all the values of an object's own properties using Object.values().
  • Write a JavaScript function that iterates through an object to collect all property values, including inherited ones.
  • Write a JavaScript function that filters an object's values to return only those of a specified type.
  • Write a JavaScript function that maps object keys to their corresponding values and returns the result as a formatted string.

Go to:


PREV : Object Properties (Own & Inherited).
NEXT : Object to Key-Value Pairs.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.