0

I have an object in javascript that contains a mix of String values along with some functions in the object. I need to loop through this object and return an array of just the String values, not the functions.

I have created an array that is set to arrayObject = Object.values(javaObject) and using a for loop to loop through this - something like this:

let objectInput = [];
for (let i = 0; i < arrayObject.length; i++) {
if(arrayObject[i] === String){
    objectInput.push(arrayObject[i]);
}
else {
    continue;
}

} return(objectInput);

This just passes right by the IF statement and can't figure out how to look for just the String values and exclude the functions from the object - any pointers?

s73c
  • 3
  • 4
  • You're missing `typeof`: `if (typeof arrayObject[i] === 'string') { ...` – Rory McCrossan Sep 29 '22 at 13:52
  • 1
    Also, you can simplify your logic by using `filter()`, then it becomes a one-liner: `let objectInput = Object.values(arrayObject).filter(v => typeof v === 'string');`. I'd also suggest you review your variable names, as the `objectInput` contains the output, and `arrayObject` seems to just be an object, not an array. – Rory McCrossan Sep 29 '22 at 13:55
  • Yes, I was just using those variables as an example really quick - I haven't started doing this exercise but do have the actual variables in place - I will try out the typeof - thank you! – s73c Sep 29 '22 at 14:17
  • 1
    @RoryMcCrossan - typeof worked like a charm!!! thank you – s73c Sep 29 '22 at 14:19

0 Answers0