4

I would like to loop through an array and get the key and value of it. This is what I'm doing, but I don't get any output. What am I doing wrong?

let regexes = [];
regexes['some.thing'] = /([^.]+)[.\s]*/g;

_.each(regexes, function(regex, key) {
    console.log(regex, key);
});
1
  • An array in Javascript has numeric indexes. If you want to iterate an object you can do it in vanilla with: for(var key in yourObjectOrArrayLike){console.log(key + ' - ' + yourObjectOrArrayLike[key]);}. Commented Jun 29, 2016 at 8:12

3 Answers 3

1

You are using array and adding a property to it which is not valid .Use object for it

let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;

_.each(regexes, function(regex, key) {
    console.log(regex, key);
});
Sign up to request clarification or add additional context in comments.

2 Comments

It is entirely valid to add a property to an array in this fashion. However it doesn't achieve the desired outcome in this case. :-)
Yes i know ,but it is not recommender and has very little use
1

_.each iterates through the indices of the array. You are adding a non-numeric property to the array object. Your array is empty and _.each callback is not executed. It seems you want to use a regular object ({}) and not an array:

let regexes = {};

Now _.each should iterate through the object own (by using hasOwnProperty method) properties.

Comments

0

You are assigning a property to the array. Lodash is attempting to iterate through the numeric indices of the array, but there are none. Change the array to an object and Lodash will iterate through its enumerable properties:

let regexes = {};
regexes['some.thing'] = /([^.]+)[.\s]*/g;

_.forEach(regexes, function(regex, key) {
    console.log(regex, key);
});

Alternatively, if using an array is necessary, simply push the value onto it:

let regexes = [];
regexes.push(/([^.]+)[.\s]*/g);

_.forEach(regexes, function(regex, i) {
    console.log(regex, i);
});

1 Comment

_.each has been deprecated in favour of _.forEach. See lodash.com/docs/4.17.4#forEach

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.