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();
Barmar
789k57 gold badges555 silver badges669 bronze badges
-
6You can't delete from JSON, you have to delete from the original object before stringifying, or parse the JSON, delete the key, then stringify again.Barmar– Barmar2023年02月07日 15:47:02 +00:00Commented Feb 7, 2023 at 15:47
-
Well you could delete it from a string as well (with some different code), but I'd say deleting it from the object is way better and easier.Mark Baijens– Mark Baijens2023年02月07日 15:51:49 +00:00Commented Feb 7, 2023 at 15:51
2 Answers 2
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"], " ")
);
answered Feb 7, 2023 at 16:13
Yogi
7,5143 gold badges34 silver badges42 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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();
answered Feb 7, 2023 at 15:56
Webdeveloper_Jelle
2,8705 gold badges37 silver badges59 bronze badges
1 Comment
Jacques tambard
Thanks for the explanation regarding the use of stringify. Afterwards it makes sense. Thanks to you Folks.
lang-js