Home > Blockchain >  Dot/Bracker Notation - dynamic keys [duplicate]
Dot/Bracker Notation - dynamic keys [duplicate]

Time:09-27

I have an object. If you drill down into the object, you have this object which is accessed via data[index].gallery.first.mobile/tablet/desktop

  "gallery": {
  "first": {
    "mobile": "./assets/product-xx99-mark-two-headphones/mobile/image-gallery-1.jpg",
    "tablet": "./assets/product-xx99-mark-two-headphones/tablet/image-gallery-1.jpg",
    "desktop": "./assets/product-xx99-mark-two-headphones/desktop/image-gallery-1.jpg"
  },       

I am trying to access these images dynamically. So for example, I have a function that will return ".mobile" etc depending on the window size. However I cannot get imageSizer's return to append to data[index].gallery.first.{return from imageSizer required here} . I am getting a mixture of undefined or [object object].mobile etc.

Also, sometimes imageSizer returns .mobile and other times it returns an array where .mobile is the only element in the array and has index of 0. It depends if I call ImageSizer on its own (returns ".mobile") or append it to data[0].gallery.first returns [object obeject][array]

const windowSizeInitial = window.innerWidth 

const imageSizer = (windowSize = windowSizeInitial) => {
    if(windowSize <= 600) {
      return ".mobile"
    } else if (windowSize <= 1400) {
      return ".tablet"
    } else {
      return ".desktop"
    }
  } 

Here is the image tag where I am trying to combine them both to get the correct dot notation needed to access the image.

src={data ? `${process.env.PUBLIC_URL}${data[0].gallery.first[imageSizer()]}` : ""} alt="product" 

Is it possible to create dynamic dot notation like I want?

Any help is appreciated! Thanks!

CodePudding user response:

Yes, you should just ditch the dot and return "mobile", "tablet" and "desktop".

E.g.:


const foo = {
  bar: "hello"
};

const key = "bar";

foo[key]; // "hello"
  • Related