JavaScript 从一个值执行 Object.entries()

标签 javascript function object

我需要创建一个从 json 对象创建组合框的函数。我得不到

"use strict"

let vars = {
  kagit: {
    "ABR": 50,
    "Krome 230 gr": 230,
    "Krome 300 gr": 300,
    "Krome 350 gr": 350,
    "Fantezi": 6,
    "Kraft": 5,
    "1. Hamur": 4
  },
 ebat: {
  "50x70 cm": 5,
  "90x126 cm": 76
 }
}

正如您从函数中看到的那样,我使用了 object.entries() 但是当我尝试执行该函数时,我无法放置从函数执行返回的参数。

function comboBox(comboValue) {

  let getValue = comboValue;

  let comboOption = document.querySelector('.' + getValue);

  let defaultOption = document.createElement('option');
  defaultOption.text = 'Lütfen Seçiniz';

  comboOption.add(defaultOption);
  comboOption.selectedIndex = 0;

  let objEnt = "vars." + getValue;

  let option;
    for (const [key, value] of Object.entries(objEnt)) {
      option = document.createElement('option');
      option.text = key;
      option.value = value;
      comboOption.add(option);
    }
    return;
}
comboBox("kagit");

最佳答案

不要将字符串传递给 Object.Entries。而是传递对象:

let vars = {
  kagit: { "ABR": 50, "Krome 230 gr": 230, "Krome 300 gr": 300, "Krome 350 gr": 350, "Fantezi": 6, "Kraft": 5, "1. Hamur": 4 },
  ebat: { "50x70 cm": 5, "90x126 cm": 76 }
}

function comboBox(comboValue) {
  // Get the chosen value from the `vars` global;
  let objEnt = vars[comboValue];

  // Now get this value's entries
  let entries = Object.entries(objEnt);

  console.log(entries)
}

comboBox("kagit");

关于JavaScript 从一个值执行 Object.entries(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51890436/

相关文章:

带有方法的 Javascript 对象返回 "has no method ' 我的方法名称'"错误

javascript - 如何分隔数组值

c++ - 如何为成员对象的过程启动新线程

javascript - JavaScript 中对象内部的 "wrapping"是如何工作的?

c# - 使用 three.js 加载 .obj 时出现问题

javascript - 使用 Meteor.loginWithFacebook 时出现内部服务器错误

javascript - 替换指定位置的部分字符串

python - 如何将值传递给公式?

javascript - 有人可以在 javascript 中解释这段代码,其中函数具有形式参数作为对象

javascript - 函数应该在 jQuery 的扩展内部还是外部?