Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

Today, we are going to learn the proper way to use an array and also remove brackets from JSON object string, here we will see the first ways to bypass removal brackets if this does not work you will also see how can we remove brackets from a JSON object.

here, we will take three types of examples, if your case from mentioned in the first and the second case then go with their solution else follow the last o third case.

Table content

  1. Use of array index
  2. Use of JSON.parse
  3. Remove brackets from JSON string

Let’s start the today’s topic How to remove square brackets from JSON objects in javascript?

Use of array index

When you have a simple array and you want to remove brackets to use their data then it’s the wrong way you have to use just array index syntax to access objects like the below example.

// your sample array
const domains = [
  {
  name: "Infinitbility",
  dob: "26-7-2020",
  domain: "infinitbility.com",
  email: "[email protected]",
  }
];

// access object values
console.log(domains[0]);

console.log(domains[0].name)

When you run the above program, you will get the object’s value in the console.

let’s check the output.

javascript, Use of array index example
javascript, Use of array index example

Use of JSON.parse()

When you are in a string that’s why you above solution does not work for you, let’s try the JSON.parse() method, it will convert your string array to an array and you can easily use it.

like the following example.

// your sample array
let domains = '[{ "name": "Infinitbility", "dob": "26-7-2020", "domain": "infinitbility.com", "email": "[email protected]"}]';

domains = JSON.parse(domains);

console.log('--------------')

// access object values
console.log(domains[0]);

console.log('--------------')
console.log(domains[0].name)

When you run the above program, it will convert JSON string to actual and you can also use it properly.

let’s check the output.

javascript, Use of JSON.parse() example
javascript, Use of JSON.parse() example

Remove brackets from JSON string

If your problem is not solved in the above case, then it’s not a problem you want to just remove brackets from the JSON string, let’s see how we can do it.

here we will use the javascript replace() method with regex exp, it will find brackets from the string and replace them with an empty string.

// your sample array
let domains = '[{ "name": "Infinitbility", "dob": "26-7-2020", "domain": "infinitbility.com", "email": "[email protected]"}]';

domains.replace(/[\[\]']+/g,'');
javascript, Remove brackets from JSON string example
javascript, Remove brackets from JSON string example

I hope it’s help you, All the best 👍.