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

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

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

1 Comment

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

Your Answer

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.