Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, we will learn to get an array from a JSON object, here we will take an example of a JSON object have stored sample array data and we will try to extract an array from JSON.

Basically, to access any JSON data we have to use their key, here we will also do the same we will use the object keys which have a store array.

Note: IF you json object in a string please parse it using JSON.parse().

For example

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

Let’s come to the topic.

Here, we will take the example of a sample object which looks like an API response, where we will get status, message, and data.

The data key has our array, and we will use the data key to access the array.

let’s understand with an example.

// sample API response
let response = {
  status: 1,
  message: "domains fetched successfully.",
  data: [
    {id: 1, name: "infinitbility", domain: "infinitbility.com"},
    {id: 2, name: "aguidehub", domain: "aguidehub.com"},
    {id: 3, name: "sortoutcode", domain: "sortoutcode.com"},
  ]
};

// try to acccess status
console.log("response status", response.status)

// try to acccess message
console.log("response message", response.message)

// try to access data
console.log("response data", response.data)

Here, we have created a sample object which has a data key with array data, and we will access the array using .data.

let’s see the output.

JavaScript, get array from json object example
JavaScript, get array from json object example

All the best 👍.