0

Let's say I have a function that receives either an object or an array. I would like to iterate through each element, and do something to each element as I go. I know that I can iterate through an array with forEach() or a normal for loop. I can also iterate through an object and array with a for in loop. But unlike the array case I have to check the object's elements with hasOwnProperty().

Can I just apply some general piece of code to both arrays and objects?

Update. This is my attempt for some object/array called value, but no console messages appear for the object case:

keysArray = Object.keys(value);
for(let key in keysArray) {
    console.log(value[key])
}
4
  • You could use Object.entries. Commented Mar 23, 2018 at 2:32
  • Perhaps lodash collection methods are of use to you? Commented Mar 23, 2018 at 2:34
  • Show some code that you understand we can take it from there. Commented Mar 23, 2018 at 2:38
  • "I have to check the object's elements with hasOwnProperty()" - no, you probably don't. And no, you shouldn't use for…in enumerations on arrays. Commented Mar 23, 2018 at 2:38

2 Answers 2

1

You could use

function* entries(o) {
    if (Array.isArray(o))
        for (let i=0; i<o.length; i++)
            yield [i, o[i]];
    else
        for (const p in o)
            yield [p, o[i]];
}
// or using builtin iterators:
function entries(o) {
    return Array.isArray(o) ? o.entries() : Object.entries(o).values();
}

and call it as

for (const [key, value] of entries(something)) {
    console.log(key, value);
}

Of course you can do a similar thing to get just the keys or just the values.

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

2 Comments

Thank you @Bergi. I'll have to look this up. Does the * declare a generator?
@chamilton Yes, that's a generator function
1
// whatever can be object or array

function doSth(whatever) {
  let myLoopable = whatever;

  // obj to array
  if (!Array.isArray(whatever)) {
    myLoopable = Object
      .keys(whatever) // get array of keys
      .reduce((acc, curKey) => [...acc, whatever[curKey]], []); // get array of values
  }

  myLoopable.forEach(value => console.log(value));
}

This is an example, not the best, you must do your own to check if it is object or not to make sure your function not failed

11 Comments

I think you want map, not reduce.
map is another choice :D. It's up to you
Well it would be a great improvement in simplicity, readability and performance…
for performance, I am sure I have no idea. for simplicity & readability, i am sure it equals. map and reduce have theirs own meaning and approach. I must agree that most people are not comfortable with reduce, but it's not because complexity.
Yes, they have their own meaning - and when you mean to map the array to a new one, you should not use reduce.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.