nb_nb_nb
nb_nb_nb

Reputation: 1381

Using .match to find in string returning weird results

I have an array of keys and an array of their corresponding values. I have been running a forEach method on the array of values to get their corresponding keys. Here is my array of keys and values I am getting from my JSON file:

keys = Object.keys(data[0]);

// result:
["Year", "month", "Day", "date", "product", "Social_Platform", "type", "p_total", "m_p_total", "d_p_total", "u_total", "m_U_total", "d_U_total", "v_total", "m_v_total", "d_v_total"]
vals = Object.values(data[0]);

// result
[2020, 1, 29, 1580256000000, "Chocos", "Twitter", "candy", 1, 0, 1, 1, 0, 1, 1, 0, 1]

forEach Method:

vals.forEach(k => {
  if (typeof k == 'string') {
    corres_key = Object.keys(data[0]).find(key => data[0][key] === k);
    arr.push(corres_key);
  } else {
    corres_key = Object.keys(data[0]).find(key => data[0][key] === k);
    if (corres_key.match(/date/gi) || corres_key.match(/dt/gi) || corres_key.match(/YEAR/gi) || corres_key.match(/DAY/gi) || corres_key.match(/MONTH/gi)) {
      console.log(corres_key);
      arr.push(corres_key);
    }
  }
});

My result:

Year
month
Day
date
month (6 times)

Why is my month getting printed 6 times? It is not doing that with any other value. Just month. Why is that happening?

I am trying to get all the keys that have string values and out of what is left I want to find all the date (date, dt, year, day, month) corresponding keys

Upvotes: 0

Views: 88

Answers (1)

alt146
alt146

Reputation: 526

"find" finds the first occurrence, so every time it looks for the key for "1" the first key with value 1 it finds is "month"

month is printed once on the second line (after Year) , and then you have another six keys with value 1's in your object

Simple code to create an object out of two arrays:

var keys = ['foo', 'bar', 'baz'];
var values = [11, 22, 33]

var result = {};
keys.forEach((key, i) => result[key] = values[i]);

Upvotes: 2

Related Questions