I’m working on the below coding challenge. My issue is returning the objects values or keys as an array. It currently returns each key / value as an individual array. I’m presuming this is because of the loop? Would really appreciate any pointers in the right direction… Many thanks!
return an array of all an objects keys or values depending on what is requested.
If the string 'values' is passed as the second argument it returns the values of
the object (obj) and if the string 'keys' is passed it must return the keys.*/
// consider these examples and use them to test your function
// getObjectData(car, 'values')
// --> ['Ford', 'Focus', 2016, 'Diesel', 150]
var person = {
firstName: 'John',
lastName: 'Smith',
age: 30,
city: 'Manchester',
area: 'Salford'
};
var car = {
make: 'Ford',
model: 'Focus',
year: 2016,
fuel: 'Diesel',
horsePower: 150
}
function getObjectData (obj, keysOrValues) {
if(keysOrValues === 'keys') {
for (var keysOrValues in obj) {
var keyArray = [];
keyArray.push(keysOrValues);
console.log(keyArray);
}
}
else if(keysOrValues === 'values') {
for (var keysOrValues in obj) {
var valueArray = [];
valueArray.push(keysOrValues);
console.log(valueArray);
}
}
}
console.log(getObjectData(car, 'values'));
Hi @123lk…I think you have identified the issue. I suspect its due to the scope of valueArray. Try defining it as a var above the for-loop and only referencing it inside the loop. Also, are you missing a return of valueArray at the end of the function?
Please open each next step only after trying to solve on your own.
###Step 1
First off, the task is to return an array. You are not returning anything, but only console.logging.
[details=Solution 1]To scaffold real quick:
function getObjectData(obj, keysOrValues) {
var resultArray = [];
//... code
return resultArray;
}
```[/details]
###Step 2
Both your loops do exactly the same, the only difference being the variable names.
[details=Solution 2]In your second loop `var keysOrValues` is a key, never a value. To get the value you need to `var val = obj[keysOrValues]`.[/details]
###Extra
You are redeclaring your function argument **keysOrValues**. It is all-right to reuse it but you shouldn't declare it as a new variable (`var`) then.
[details=Solution All]After the changes:
```javascript
function getObjectData(obj, keysOrValues) {
var resultArray = [];
if(keysOrValues === 'keys') {
for (var key in obj) {
resultArray.push(key);
}
} else if(keysOrValues === 'values') {
for (var key in obj) {
var value = obj[key];
resultArray.push(value);
}
}
return resultArray;
}
Or you can move condition inside the loop:
function getObjectData(obj, keysOrValues) {
var resultArray = [];
for (var key in obj) {
resultArray.push(keysOrValues === 'keys' ? key : obj[key]);
}
return resultArray;
}
```[/details]