0

I am trying to get values from an object containing values (which are arrays) dynamically. when I click o a div I fetched custom data attribute and then tried to used to get a value from the object but it didn't work. please suggest how can I fix this code or suggest another approach.

const livingRroomsVar = [];
for (let i = 1; i < 18; i++) {
    livingRroomsVar.push(i + String(".jfif"));
}
const kitchensVar = [];
for (let i = 1; i < 13; i++) {
    kitchensVar.push(i + String(".jfif"));
}
// the object I am trying to get the values from
const filteredArray = {
    livingRrooms: livingRroomsVar,
    kitchens: kitchensVar,
};
console.log(filteredArray.kitchens);
// resutlt : 
//Array(12)
//this dose not match when getting it by clicking div below
$(".div1").on("click", function() {
    console.log($(this).data("val"));
    nameVAl = $(this).data("val");
    console.log(filteredArray.nameVAl);
// result : 
//undefined
});
<div data-val="livingRrooms" class="div1 red">first div</div>
<div data-val="kitchens" class="div1 blue">second div</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • You're looking for `filteredArray[nameVAl]`. (Side note: Don't forget to declare your variables, right now your code is falling prey to what I call [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html).) – T.J. Crowder Jul 18 '21 at 11:17
  • Make changes to this line. `const nameVAl = $(this).data("val"); console.log(filteredArray[nameVAl]);` – Mohammad Abu Musâ Robı Jul 18 '21 at 11:45

0 Answers0