Jacques tambard
Jacques tambard

Reputation: 49

remove key(s) from a json array under javascript

Need to remove key(s) from a json array under javascript (jquery). Looks like my code is wong although it was working in my Chrome console. Your help is the most welcome. 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();

Upvotes: 0

Views: 262

Answers (2)

Yogi
Yogi

Reputation: 7184

JSON.stringify has an often overlooked parameter called the replacer. It can accept an array of key names to include in the json output:

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

Snippet

Run the snippet to see the output with and without using the replacer.

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"], " ")
);

Upvotes: 1

Webdeveloper_Jelle
Webdeveloper_Jelle

Reputation: 2856

You should not stringify the object before removing the key.

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();

Upvotes: 0

Related Questions