Objects and Arrays in Java Script


 Objects and Arrays in Java Script

In JavaScript, objects and arrays are two fundamental data structures used to store and organize data.


Objects

An object is a collection of key-value pairs, where each key is a string (also called a property name) and each value can be of any data type (e.g. string, number, boolean, function, or another object). Objects are created using curly braces {} and properties are accessed using dot notation or square bracket notation.


const person = {

  name: 'John',

  age: 25,

  hobbies: ['reading', 'music', 'sports'],

  address: {

    street: '123 Main St',

    city: 'New York',

    state: 'NY',

    zip: '10001'

  }

};


console.log(person.name); // John

console.log(person.hobbies[1]); // music

console.log(person.address.city); // New York


Arrays

An array is an ordered list of values, which can be of any data type. Arrays are created using square brackets [] and elements are accessed using index notation, starting at 0.


const numbers = [1, 2, 3, 4, 5];

const colors = ['red', 'green', 'blue'];


console.log(numbers[2]); // 3

console.log(colors[1]); // green




Objects and arrays are extensively used in web designing for storing and manipulating data. 


Objects


Storing and accessing data related to web pages or user interfaces, such as user profiles, product information, or settings.

Representing and manipulating graphical elements on a web page, such as HTML elements, CSS styles, or SVG graphics.

Creating and managing user sessions and authentication tokens for secure web applications.

Storing and manipulating data related to forms and user input, such as validation rules, input values, or error messages.

Managing and processing multimedia content, such as images, videos, or audio, for media-rich web pages or applications.


Program : Using Objects for Data Validation


// define a validate function that checks if a given input object has all required properties

function validate(input) {

  const requiredProperties = ['name', 'email', 'password'];

  const missingProperties = [];


  requiredProperties.forEach(prop => {

    if (!input[prop]) {

      missingProperties.push(prop);

    }

  });


  if (missingProperties.length > 0) {

    console.log(`Missing properties: ${missingProperties.join(', ')}`);

  } else {

    console.log('Input is valid');

  }

}


// test the validate function with different input objects

const input1 = {

  name: 'John Doe',

  email: 'john.doe@example.com'

};

const input2 = {

  name: 'Jane Smith',

  password: 'password123'

};

const input3 = {

  email: 'joe@example.com',

  password: 'pass123'

};


validate(input1);

validate(input2);

validate(input3);


OutPut :

Missing properties: password

Missing properties: email

Missing properties: name, password


Arrays


Implementing and managing data structures and algorithms, such as linked lists, hash tables, or sorting algorithms, for various web applications or games.

Building and manipulating user interface components, such as tables, lists, or charts, for data visualization or dashboard applications.

Storing and processing large datasets or streams of data, such as log files, sensor data, or real-time analytics data, for web applications or services.

Implementing data-driven business logic and workflows, such as order processing, inventory management, or customer relationship management, for e-commerce or enterprise web applications.

Storing and accessing lists or collections of data, such as menus, navigation items, or search results.

Building and manipulating dynamic web interfaces, such as galleries, carousels, or grids.

Sorting and filtering data based on user preferences or search queries.

Implementing data structures and algorithms, such as stacks, queues, or trees, for various web applications or games.


Program 1: Sorting and Filtering an Array


// create an array of numbers

const numbers = [5, 2, 8, 1, 9, 4];


// sort the array in ascending order

numbers.sort((a, b) => a - b);


// filter out all odd numbers

const evenNumbers = numbers.filter(num => num % 2 === 0);


console.log(numbers);

console.log(evenNumbers);


OutPut :

[1, 2, 4, 5, 8, 9]

[2, 4, 8]


Program 2: Building a Todo List


// create an empty todo list array

const todoList = [];


// define a function to add a new item to the todo list

function addItem(item) {

  todoList.push({

    id: todoList.length + 1,

    text: item,

    completed: false

  });

}


// define a function to toggle the completed status of a todo item

function toggleCompleted(id) {

  const todoItem = todoList.find(item => item.id === id);

  if (todoItem) {

    todoItem.completed = !todoItem.completed;

  }

}


// add some sample items to the todo list

addItem('Buy groceries');

addItem('Do laundry');

addItem('Pay bills');


// toggle the completed status of the first item

toggleCompleted(1);


console.log(todoList);


OutPut:

[

  { id: 1, text: 'Buy groceries', completed: true },

  { id: 2, text: 'Do laundry', completed: false },

  { id: 3, text: 'Pay bills', completed: false }

]


Post a Comment

Previous Post Next Post