0

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
asked Feb 7, 2023 at 15:45
2
  • 6
    You 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. Commented 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. Commented Feb 7, 2023 at 15:51

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thanks for the explanation regarding the use of stringify. Afterwards it makes sense. Thanks to you Folks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.