JavaScript Adding array name property to JSON object [ES5] and display in Console?

In JavaScript, you can add a JSON object to an array and assign it a property name for better organization. This is useful when you need to convert object data into array format while maintaining structure.

Initial Object Setup

Let's start with a sample customer object:

var customerDetails = {
    "customerFirstName": "David",
    "customerLastName": "Miller",
    "customerAge": 21,
    "customerCountryName": "US"
};

Adding Object to Array Using push()

Create a new array and use the push() method to add the object. This converts the object into an array element:

var customerDetails = {
    "customerFirstName": "David",
    "customerLastName": "Miller",
    "customerAge": 21,
    "customerCountryName": "US"
};

var customerObjectToArray = [];
customerObjectToArray.push(customerDetails);
console.log(customerObjectToArray);
[
  {
    customerFirstName: 'David',
    customerLastName: 'Miller',
    customerAge: 21,
    customerCountryName: 'US'
  }
]

Adding Multiple Objects with Named Properties

You can also add multiple objects with specific array names or create named collections:

var customerDetails = {
    "customerFirstName": "David",
    "customerLastName": "Miller",
    "customerAge": 21,
    "customerCountryName": "US"
};

var anotherCustomer = {
    "customerFirstName": "John",
    "customerLastName": "Smith",
    "customerAge": 25,
    "customerCountryName": "UK"
};

var customerArray = [];
customerArray.push(customerDetails, anotherCustomer);
console.log("Customer Array:", customerArray);
Customer Array: [
  {
    customerFirstName: 'David',
    customerLastName: 'Miller',
    customerAge: 21,
    customerCountryName: 'US'
  },
  {
    customerFirstName: 'John',
    customerLastName: 'Smith',
    customerAge: 25,
    customerCountryName: 'UK'
  }
]

Alternative: Direct Array Assignment

You can also directly assign objects to array indices with meaningful names:

var customerDetails = {
    "customerFirstName": "David",
    "customerLastName": "Miller",
    "customerAge": 21,
    "customerCountryName": "US"
};

var customers = [customerDetails];
customers.arrayName = "CustomerCollection";
console.log("Array with name property:", customers);
console.log("Array name:", customers.arrayName);
Array with name property: [
  {
    customerFirstName: 'David',
    customerLastName: 'Miller',
    customerAge: 21,
    customerCountryName: 'US'
  }
]
Array name: CustomerCollection

Conclusion

Using push() method effectively converts JSON objects into array elements, making data manipulation easier. You can also add custom properties to arrays for better identification and organization of your data collections.

Updated on: 2026-03-15T23:18:59+05:30

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements