在javascript下从json数组中删除键

j9per5c4  于 2023-02-10  发布在  Java
关注(0)|答案(2)|浏览(192)

需要从javascript(jquery)下的json数组中删除键。看起来我的代码是wong,虽然它在我的Chrome控制台中工作。您的帮助是最受欢迎的。Jacques

function test() {
  var json = {
    "ID": "2196",
    "VERSION": "1-2022",
    "FILE": "2196.docx"
  };
  json = JSON.stringify(json)
  console.log("json " + json);

  delete json['FILE'];
  console.log("json " + json);
  return;
}

test();
xbp102n0

xbp102n01#

stringify有一个经常被忽略的参数replacer,它可以接受一个键名数组包含在json输出中:

JSON.stringify(data, ["ID","VERSION"], " ");  // FILE is excluded
    • 片段**

运行代码段以查看使用和不使用替换器的输出。

let data = {
  "ID": "2196",
  "VERSION": "1-2022",
  "FILE": "2196.docx"
};

console.log("Without replacer: ",
  JSON.stringify(data, null, " ")
);

console.log("Using replacer: ",
  JSON.stringify(data, ["ID","VERSION"], " ")
);
eqzww0vc

eqzww0vc2#

在删除密钥之前,您不应stringify对象。

function test() {
  var json = {
    "ID": "2196",
    "VERSION": "1-2022",
    "FILE": "2196.docx"
  };
  // stringify to show in console as string
  json = JSON.stringify(json)
  console.log("json " + json);

  // convert back to object so you can remove the key
  json = JSON.parse(json);
  delete json['FILE'];
  
  // stringify to show new object in console as string
  json = JSON.stringify(json);
  console.log("json " + json);
  return;
}

test();

相关问题