【问题标题】:Find the value from json where key is in another variable从 json 中查找 key 在另一个变量中的值
【发布时间】:2023-03-17 05:45:01
【问题描述】:

假设我们有类似的 json 对象,

  const land={
  water : "cool",
   air  : "heat"
}

现在如果 key = "water";

如何找到价值,而不是像这个land.water; 只需按键,也无需循环

就像

  console.log(land.key); //but its not working 

请帮助我.. 花了将近 4 小时但无法找到解决方案。

【问题讨论】:

  • 试试land[key]
  • 谢谢你,兄弟……它成功了……

标签: javascript node.js json


【解决方案1】:

使用变量并使用square bracket notationland 检索属性:

const land= {
  water: "cool",
  air: "heat"
};
const h2o = "water";
console.log(land[h2o]);

// all keys from land
const [wtr, pfft] = Object.keys(land);
console.log(land[pfft]);

【讨论】:

    【解决方案2】:

    这对我有用 `常量土地={ 水:“酷”, 空气:“热” }

    console.log(land.water)` 结果很酷。 您只需使用密钥即可获得价值。

    【讨论】:

      【解决方案3】:

      const land = {
        water: "cool",
        air: "heat"
      };
      const h2o = "water";
      console.log(land[h2o]);

      【讨论】:

        【解决方案4】:

        const land ={
        water:'cool',
        air:'heat'
        }
        
        let {water:someOtherName} = land
        
        console.log(someOtherName)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-07
          • 2017-06-06
          • 1970-01-01
          • 1970-01-01
          • 2017-11-27
          • 1970-01-01
          • 1970-01-01
          • 2012-06-07
          相关资源
          最近更新 更多