【问题标题】:a parameter of a function to access a json key in javascript , node用于访问 javascript 中的 json 键的函数的参数,节点
【发布时间】:2020-10-29 13:10:12
【问题描述】:

我有一个包含 10 个元素的 json,如下所示: {"id":"2","name":"Peter","number":"A4584857","father":"Gerart","color":"green"}

我尝试修改 json,所以我有一个像这样读写的函数:

function updatefilelocal(id,texto) {
   const fs = require('fs');
    fs.readFile('students.json', (err, data) => {  

      if (err) throw err;
      let json = JSON.parse(data); 
      console.log('This is after the read call')

      const filename='students.json';
      var file=json; 
    
      file.alumnos[id].color= texto

      fs.writeFile(filename,JSON.stringify(file),function writeJson(err){
        if (err)return console.log(err);
        //console.log(JSON.stringify(file));
        //console.log('writing to'+filename )
    
      });
    });
}

所以,用这一行:file.alumnos[id].color= texto 和这个函数:updatefilelocal(2,'yellow') 我可以修改我的 json 中的键颜色,嗯,它有效,但是当我想修改我的元素的键“名称”时像这样更改名称的颜色:file.alumnos[id].name= texto 没关系,但我想做的是在我的函数中添加第三个参数: function updatefilelocal(id,texto,third_parameter) {...} 更改“名称”上的“颜色”。我会这样调用我的函数:updatefilelocal(id,texto,name) 如果我想更改元素的名称或 updatefilelocal(id,texto,color) 如果我想改变元素的颜色...我已经尝试了所有...我已经放了括号file.alumnos[id].{third parameter}= texto 但没有任何效果... 感谢您的帮助。

【问题讨论】:

  • 请在此处发布您的 json 结构。它是一个数组吗?还是具有这些键/值的对象?
  • {"alumnos":[ {"id":"1","name":"Peter","number":"A4584837","father":"Gerart","color" :"green"},{"id":"2","name":"Maria","number":"A4584857","father":"pett","color":"yellow"},{" id":"3","name":"John","number":"A4584857","father":"Juan","color":"green"},etc...]}

标签: javascript node.js json parameter-passing


【解决方案1】:

您可以将密钥作为第三个参数传入,并使用[key] 访问它。所以你的代码中的一个例子是:

function updatefilelocal(id, texto, key) {
  // Your code
  file.alumnos[id][key] = texto;
  // Rest of your code
}

您可以选择更改颜色或名称,方法是使用updatefilelocal(id, texto, 'color')updatefilelocal(id, texto, 'name') 调用updatefilelocal

下面是一个例子,看看它是如何工作的:

let x = { a: 1, b: 2 };

function changeKeyValue(obj, key, val) {
  obj[key] = val;
}

changeKeyValue(x, 'a', 3); // x = { a: 3, b: 2 }
changeKeyValue(x, 'b', 4); // x = { a: 3, b: 4 }

【讨论】:

  • 太棒了!我不知道这种方式。非常感谢@JY Loh!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 2017-11-07
相关资源
最近更新 更多