【问题标题】:How use input.value and get key from object如何使用 input.value 并从对象中获取密钥
【发布时间】:2021-04-26 13:52:15
【问题描述】:

您好,有人可以帮我解决这个问题吗? 我想在输入中写“company1”,将它与 input.value 一起显示在 score(paragraph) 中。

它应该看起来像“写company1并显示在分数foil1、foil2和foil3中”

const input = document.querySelector('input');
const score = document.querySelector('.score');

const prices = {
    'company1': {
        'foil1': {
            '0-5000m2' : 0.67,
            '5000-10000m2' : 0.65,
            '10000-20000m2' : 0.63
        },
        'foil2': {
            '0-5000m2' : 0.67,
            '5000-10000m2' : 0.65,
            '10000-20000m2' : 0.63
        },
        'foil': {
            '0-5000m2' : 0.67,
            '5000-10000m2' : 0.65,
            '10000-20000m2' : 0.63
        }
    }
}

btnSearch.addEventListener('click',()=>{

const company = input.value;
const foil = Object.keys(company) - I know that here is problem, but dont know how make it correctly
console.log(foil); and here is problem becasue its return numbers = Array(8) [ "0", "1", "2", "3", "4", "5", "6", "7" ]
})

【问题讨论】:

    标签: javascript object key


    【解决方案1】:

    你可以在下面喜欢这个。公司名称是prices 的键。所以你应该将变量作为键传递。并使用 Object.values 然后只有你得到对象值。这意味着对象的右侧

    Object.values(prices[company])
    

    const input = document.querySelector('input');
    const btnSearch = document.querySelector('button');
    
    
    const prices = { 'company1': { 'foil1': { '0-5000m2' : 0.67, '5000-10000m2' : 0.65, '10000-20000m2' : 0.63 }, 'foil2': { '0-5000m2' : 0.67, '5000-10000m2' : 0.65, '10000-20000m2' : 0.63 }, 'foil': { '0-5000m2' : 0.67, '5000-10000m2' : 0.65, '10000-20000m2' : 0.63 } } }
    
    btnSearch.addEventListener('click', () => {
      const company = input.value;
      const foil = Object.values(prices[company])
      console.log(foil)
    })
    <input value="company1"/>
    <button type="button">click</button>

    【讨论】:

      【解决方案2】:

      你应该做Object.keys(prices),对吧?

      您能否澄清一下您真正想要做什么?那么我可以更好地帮助你。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-25
        • 2018-12-30
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        相关资源
        最近更新 更多