如何访问嵌套对象键

时间:2018-12-27 12:11:20

标签: javascript

我正在尝试从具有嵌套对象的数据文件中获取值。

我想为EN对象下的每个条目创建一个标签。因此,我想最终得到一个“邮件” 标签,一个“报价” 标签和一个“电话” 标签。

在标签中,我想通过访问 tabLabel tabIcon 的内容。

使用 Object.Keys(),我可以看到字符串,但是当我尝试 console.log 时,它们却得到未定义

我执行了此功能,但是不起作用:

>tr|Q8IBQ5|Q8IBQ5_PLAF7
MDKQTLPHHKYSYIPKQNKKLIYEYLFKEGVIVVEKDAKIPRHPHLNVPNLHIMMTLKSL
KSRNYVEEKYNWKHQYFILNNEGIEYLREFLHLPPSIFPATLSKKTVNRAPKMDEDISRD
VRQPMGRGRAFDRRPFE
>tr|Q8IEB1|Q8IEB1_PLAF7
EYKLEFLSYLLIFKKKNERISKFDEQIKTCINIFEKSIINESDLKYLFERNILDMNPGV
RSMCWKLALKHLSLDSNKWNTELIEKKKLYEEYIKSFVINPYYSCVDNKKKEFVKETEKE
PKGKNMKDEYIEYNLDRNKTYYHKDDSLLKLQNDNNTKQMDYLEDEKYSSMDDECSEDNW

这是数据:

function generateLabel() {
  const keys = Object.keys(TabFormData.EN);
  for (let i = 0; i < keys; i += 1) {
    return `
      <div class="${ID}_tab-form__headerItemWrap">
        <label for="taLabel-here"><i class="tabIcon-here"></i></label>
      </div>
    `;
  }
}

4 个答案:

答案 0 :(得分:2)

您的问题出在循环中。

for (let i = 0; i < keys; i += 1)

在这里,您要检查i是否小于数组对象,这不是您想要的。 您想将i与数组中的项目数进行比较。

那将变成这样:

for (let i = 0; i < keys.length; i += 1)

您的字符串文字也是错误的,在这种情况下,ID是未定义的变量。我假设您想要密钥的名称。对于此问题,它应变为:

<div class="${keys[i]}_tab-form__headerItemWrap">

此外,一旦您从for循环中return,它将在第一次迭代时自动中断(这意味着您将始终只获得一个项目)。您可以做的是先构建整个字符串,然后返回它。

这会使您的功能变为:

function generateLabel() {
  const keys = Object.keys(TabFormData.EN);
  var str = "";
  for (let i = 0; i < keys.length; i += 1) {
    str +=
      `<div class="${keys[i]}_tab-form__headerItemWrap">
        <label for="taLabel-here"><i class="tabIcon-here"></i></label>
      </div>
    `;
  }

  return str;
}

Here's a Fiddle.

答案 1 :(得分:0)

正如@ Adriani6所报告的那样,您在循环中遇到了问题,但是要真正回答您的问题,这里是如何访问嵌套对象的方法:

function generateLabel() {
    const keys = Object.keys(TabFormData.EN);
    for (let i = 0; i < keys.length; i += 1) {
        let currentTabObject = TabFormData.EN[keys[i]];
        console.log(currentTabObject[0].tabLabel);
        console.log(currentTabObject[0].tabIcon);
    }
}

答案 2 :(得分:0)

如果我理解正确,那么您正在寻找如下内容:

# convert certificate chain + private key to the PKCS#12 file format
openssl pkcs12 -export -out keystore.pkcs12 -in fullchain.pem -inkey privkey.pem

# convert PKCS#12 file into Java keystore format
keytool -importkeystore -srckeystore keystore.pkcs12 -srcstoretype PKCS12 -destkeystore keystore.jks

Object.keys()仅返回对象的键,但是似乎您也想访问这些值。因此,在您的情况下,首选 Object.entries()

我建议阅读以下链接: https://javascript.info/keys-values-entries

答案 3 :(得分:0)

Assuming you assign TabFormData.EN to a variable called data and the Object.keys result of TabFormData.EN to a variable called keys, you can use:

  • ${keys[i]} to retrieve the name and append it to your div classname,
  • ${data[keys[i]][0].tabLabel} to retrieve the tabLabel property value and append it to your <label> tag, and
  • ${data[keys[i]][0].tabIcon} to retrieve the tabIcon property value and append it to your <i> tag.

You can ignore the <hr> tags, the <button> tag and the rendered <div> tags and just check the object property references in the code snippet below if you want. They are just there for illustrating the code results in the jsFiddle and the code snippet below:

/* JavaScript */
var x = document.getElementById('abc');
var btn = document.getElementById('btn');

function generateLabel() {
  const data = TabFormData.EN;
  const keys = Object.keys(data);
  
  for (let i = 0; i < keys.length; i += 1) {
    x.innerHTML += `
    	<hr>
          <div class="${keys[i]}_tab-form__headerItemWrap">
            <label for="${data[keys[i]][0].tabLabel}">
              <i class="${data[keys[i]][0].tabIcon}-here">
                  class of this div is ${keys[i]}_tab-form__headerItemWrap, label for this is ${data[keys[i]][0].tabLabel} and icon is ${data[keys[i]][0].tabIcon}
              </i>
            </label>
          </div>
        <hr>`
  }
}

btn.addEventListener('click', generateLabel);

const TabFormData = {
  EN: {
    mail: [
      {
        tabLabel: 'Email Our Team',
        tabIcon: 'fa fa-envelope',
      },
      {
        label: 'First Name',
        type: 'text',
        name: 'name',
        required: true,
        hint: 'Please, provide your Name.',
      },
      {
        label: 'Last Name',
        type: 'text',
        name: 'surname',
        required: true,
        hint: 'Please, provide your Last Name.',
      },
      {
        label: 'Email Address',
        type: 'email',
        name: 'email',
        required: true,
        hint: 'Please, provide a valid email.',
      },
      {
        label: 'Your Message',
        type: 'textarea',
        required: true,
        name: 'message',
        hint: 'Write us a message.',
        rows: 20,
        cols: 50,
      },
      {
        label: 'About You',
        required: true,
        select: [
          'Home use',
          'Business use',
          'Freelance, professional',
        ],
      },
    ],
    quote: [
      {
        tabLabel: 'Request a Quote',
        tabIcon: 'fa fa-file-invoice-dollar',
      },
      {
        label: 'First Name',
        type: 'text',
        name: 'name',
        required: true,
        hint: 'Please, provide your Name.',
      },
      {
        label: 'Last Name',
        type: 'text',
        name: 'surname',
        required: true,
        hint: 'Please, provide your Last Name.',
      },
      {
        label: 'Phone Number',
        type: 'number',
        name: 'telephone',
        required: true,
        hint: 'Please, provide a valid number',
      },
      {
        label: 'Email Address',
        type: 'email',
        name: 'email',
        required: false,
        hint: 'Please, provide a valid email.',
      },
      {
        label: 'Your Message',
        type: 'textarea',
        required: false,
        name: 'message',
        hint: 'Write us a message.',
        rows: 20,
        cols: 50,
      },
      {
        label: 'About You',
        required: true,
        select: [
          'Home use',
          'Business use',
          'Freelance, professional',
        ],
      },
    ],
    call: [
      {
        tabLabel: 'Call Me Back',
        tabIcon: 'fa fa-phone',
      },
      {
        label: 'First Name',
        type: 'text',
        name: 'name',
        required: true,
        hint: 'Please, provide your Name.',
      },
      {
        label: 'Last Name',
        type: 'text',
        name: 'surname',
        required: true,
        hint: 'Please, provide your Last Name.',
      },
      {
        label: 'Phone Number',
        type: 'number',
        name: 'telephone',
        required: true,
        hint: 'Please, provide a valid number',
      },
      {
        label: 'About You',
        required: true,
        select: [
          'Home use',
          'Business use',
          'Freelance, professional',
        ],
      },
    ],
  },
  IT: {

  },
};
/* CSS */
<!-- HTML -->

<button id="btn">
Click Me
</button>
<div id="abc"></div>