Author avatar

Pavneet Singh

Delete Data from JSON Using a Key in React

Pavneet Singh

  • Nov 9, 2020
  • 4 Min read
  • 99 Views
  • Nov 9, 2020
  • 4 Min read
  • 99 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

JavaScript Object Notation (JSON) is a widely popular key-value-based data format used to store and transfer data. JSON uses basic data types, such as string, boolean, int, decimal, object, arrays, and null, to transfer data using predefined hierarchy and key-value pairs. Due to its concise structure and durability, JSON is supported by most development platforms, No-SQL databases, REST, GraphQL, and so on.

A JSON string can easily be converted to a JavaScript object by using JSON API to directly access the data by using dot notation and keys. The inbuilt JSON support allows you to easily integrate REST APIs, data management, and dynamic component design in React. This guide explains the steps to parse JSON data and perform the delete operation on a nested JSON object using a key as input.

Create a JSON Object

A JSON object is represented using a pair of curly braces ({}), and the key-value is separated by using a colon (:). A JSON string can be created using a combination of single and double quotes:

1
let jsonStr = '{"name":"ABC", "age":10 }';
JS

Note: JSON strings must only use double quotes to wrap key and values. Use single quotes to wrap a JSON string. The jsonStr can be converted to a JavaScript object using the parse method:

1
2
let jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.name, jsonObj.age); // ABC : 10
JS

The eval function is also used for parsing:

1
let jsonObj = eval('('+jsonStr+')');
JS

The use of eval is not recommended because eval can used as a loophole to run malformed instructions, though unlike the parse function, eval can transform a JSON string wrapped in double quotes:

1
let jsonObj = eval('('+ "{'name':'ABC', 'age':10 }" +')');
JS

Delete Data from JSON String using Regular Expressions

Regular expressions can be used to find and replace a specific portion of a string using the replace function. A pair of double quotes with key can be used to create a pattern:

1
2
3
4
5
let jsonStr = '{"name":"ABC", "age":10 }';
let key = "age";
let cleanJsonRegex = new RegExp(`,.*${key}.*[, ]`, "g");
let nameJsonStr = jsonStr.replace(cleanJsonRegex, "");
console.log(nameJsonStr); // "{\"name\":\"ABC\"}"
JS

The cleanJsonRegex object defines the pattern to match a specific key-value pair, and it can be explained as:

  • , match a comma character
  • .* match zero or more character except for line terminators (\n)
  • ${key}.* match the exact value of key and zero or more characters after the key
  • [, ] match either a comma or space
  • g flag will match all possible matches in the jsonStr

The replace function finds and replaces the matched data from the jsonStr and returns a resultant string.

Note: Regular expressions are quite powerful but they are also fragile so always avoid the use of regular expressions with complex data.

Delete Data from JSON using JavaScript Objects

JavaScript objects offer a convenient way to access JSON data using dot notation and indexes for JSON arrays. Use the parse function to convert a JSON string to JavaScript object:

1
2
let jsonStr = '{"name":"ABC", "age":10, "phone":["1234567890","1234567890"]}';
let jsonObj = JSON.parse(jsonStr);
JS

The delete operator can be used to remove a key-value pair from a JavaScript object:

1
2
3
4
5
6
7
delete jsonObj.name;
/* after delete
{
  age: 10,
  phone: ["1234567890", "1234567890"]
}
*/
JS

Alternately, string keys can be used to delete a key-value pair:

1
2
let key = 'name';
delete jsonObj[key];
JS

The advantage of using string keys with a JavaScript object is that it allows the use of keys having special characters:

1
delete jsonObj['class.name'];
JS

Tips

• Use stringify to covert a JavaScript object to a JSON string:

1
2
let obj = {name: "ABC"};
console.log(JSON.stringify(obj));
JS

• Use toJSON to get string representation of date objects. • For better support, use typescript for static type checking support.

Conclusion

JSON and JavaScript objects have almost the same syntax and inbuilt browser support to parse JSON string as a JavaScript object. Always prefer the use of JavaScript objects to access JSON data. Happy coding!

0