简体   繁体   中英

how to access values of an object with dynamic keys?

I have this code

    bodyLength.map((el, i) => {
      console.log(`${values.bodyTitleEn2 + i.toString()}`);

      body.push({
        title: [
          {
            key: 'en',
            value: values.bodyTitleEn + i,
          },
          {
            key: 'ku',
            value: values.bodyTitleKu + i,
          },
          {
            key: 'ar',
            value: values.bodyTitleAr + i,
          },
        ] ...

values.bodyTitleEn , Ku , and Ar have a number at the end of them, which means values.bodyTitleEn0 , values.bodyTitleEn1 , values.bodyTitleEn2 , and I have this array bodyLength which is equal to the length of how many of bodyTitle[En] are there, so I'm trying to achieve values.bodyTitleEn + i to add the number at the end dynamically, but it says undefined values.bodyTitleEn , because bodyTitleEn never exists in the object without the number at the end of it, how can I achieve this thanks.

You can append the number like this:

values[`bodyTitleEn${i}`]

the above syntax will try to get the value of the key bodyTitleEn0 , bodyTitleEn1 ...

when you use values.bodyTitleEn + i , you're trying to add the number to the value returned by values.bodyTitleEn but like you noticed the values object doesn't have the key bodyTitleEn and even if it has the key, that's not what you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM