0

I need to write a function that takes in an object and returns an array with this object's property values.

Ex.:

var obj = {
    name: "Joao",
    age: 27,
    country: "USA"
};

The function should return an array like this:

var array = ["John", 27, "USA"]; 

I can't use Object.values().

That's how my last attempt looks like:

function returnValues(obj) {
    for (var key in obj) {
    return obj[key];
}

It does not return an array with the values. Can anyone help me?

1

4 Answers 4

6

You could try using map:

var obj = {
    name: "Joao",
    age: 27,
    country: "USA"
};

var array = Object.keys(obj).map(item => obj[item]);

console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

4

You can either use Object.keys and iterate over that to return the values:

function returnValues(obj) {
    return Object.keys(obj).map(function(key) {
       return obj[key];
    });
}

Or you can create a temp array using your existing solution:

function returnValues(obj) {
    var temp = [];
    for (var key in obj) {
       temp.push(obj[key]);
    }
    return temp;
}

With ES6 support you can shorten to:

const returnValues = (o) => Object.keys(o).map(k => o[k]);

Or use Object.entries:

Object.entries(obj).map(([,v]) => v)

Or as @ibrahim mahrir points out, if you have ES2017 support you can use Object.values:

console.log(Object.values(obj));

3 Comments

Thanks @ibrahimmahrir. Add ALL THE SOLUTIONS! :P
@ibrahimmahrir I wish I could donate the upvote I received for this answer to you :P - updated
I'm so happy just to help!
2

Add it to an array and then return the array

function returnValues(obj) {
    var arr = [];
    for (var key in obj)
       arr.push(obj[key]);
    return arr;
}

Comments

0

You can also use Object.entries().

var obj = {name: "Joao", age: 27, country: "USA"},
    elems = Object.entries(obj).map(v => v[1]);

    console.log(elems);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.