Associative Arrays and Objects Associative Arrays, Objects Svetlin Nakov Technical Trainer Software University

Slides:



Advertisements
Similar presentations
JavaScript Basics Course Introduction SoftUni Team Technical Trainers Software University
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
Svetlin Nakov Technical Trainer Software University Functions and Objects Reusable Parts of Code Objects in JavaScript.
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
Database APIs and Wrappers
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
JavaScript Best Practices Learn How to Write Better Quality JavaScript Software University Technical Trainers SoftUni Team.
JavaScript Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Java Collections Basics Arrays, Lists, Strings, Sets, Maps Svetlin Nakov Technical Trainer Software University
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Svetlin Nakov Technical Trainer Software University Functions and Objects Reusable Parts of Code Objects in JavaScript.
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
JavaScript Applications Course Introduction SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Simulating OOP in JavaScript Function Constructor, Prototypes, "this" Object, Classical and Prototypal Model Software University Technical.
Operators and Expressions
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Advanced Tree Structures Binary Trees, AVL Tree, Red-Black Tree, B-Trees, Heaps SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Extending functionality using Collections
Exporting and Importing Data
Presentation transcript:

Associative Arrays and Objects Associative Arrays, Objects Svetlin Nakov Technical Trainer Software University

Table of Contents 1.Associative Arrays 2.Object Types 3.JavaScript Objects Overview 4.JSON Objects 5.lodash.js 2

Associative Arrays

4  Associative arrays in JavaScript are called Objects holding a set of key-value pairs Associative Arrays (Maps, Dictionaries)  Traditional array  Associative array orange2.30apple1.50 tomato3.80 key value key value

5  Initializing an associative array (object):  Accessing elements by index:  Inserting a new element / deleting element:  Objects are not arrays  no length, no slice(), no join(), … Associative Arrays in JavaScript var prices = { 'orange' : 2.30, 'apple' : 1.50, 'tomato' : 3.80 }; console.log(prices['orange']); // 2.3 prices['cucumber'] = 1.25; delete prices['orange']; console.log(prices); // {apple: 1.5, tomato: 3.8, cucumber: 1.25}

6  Processing associative arrays (objects) by for-in loop  Taking the keys of object / array: Processing Associative Arrays var prices = {'orange' : 2.30, 'apple' : 1.50, 'tomato' : 3.80 }; for (key in prices) { console.log(key + ' -> ' + prices[key]); console.log(key + ' -> ' + prices[key]);} var prices = { 'orange' : 2.30, 'apple' : 1.50, 'tomato' : 3.80 }; console.log(Object.keys(prices)); // ["orange", "apple", "tomato"] var nums = [10, 20, 30]; console.log(Object.keys(nums)); // ["0", "1", "2"]

Object Types and Objects Modeling Real-world Entities with Objects

 Software objects model real-world objects or abstract concepts  Examples:  bank, account, customer, dog, bicycle, queue  Real-world objects have state and behavior  Account's state:  holder, balance, type  Account's behavior:  withdraw, deposit, suspend What are Objects?

9  How do software objects implement real-world objects?  Use variables / data to implement state  Use methods / functions to implement behavior  An object is a software bundle of variables and related functions What are Objects? (2) account owner: "Peter" balance: function deposit(sum) function withdraw(sum) state (data) (functions) behavior (functions)

10 Objects Represent  checks  people  shopping list …  numbers  characters  queues  arrays Things / concepts from the real world Things / concepts from the computer world

11  The formal definition of a object type (class): Definition by Google What is an Object Type (Class)? Object types act as templates from which an instance of an object is created at run time. Types define the properties of the object and the functions used to control the object's behavior.

12  Object types provide the structure for objects  Define their prototype, act as template  Object types define:  Set of attributes  Represented by variables and properties  Hold their state  Set of actions (behavior)  Represented by methods/functions Object Types

13  An object is a concrete instance of a particular object type  Creating an object from an object type is called instantiation  Objects have state  Set of values associated to their attributes  Example:  Type: Account  Objects: Ivan's account, Peter's account Objects

14 Object Types and Objects – Example Account ownerbalance suspend()deposit(sum)withdraw(sum) Object type ivanAccount owner = "Ivan Kolev" balance = peterAccount owner = "Peter Kirov" balance = kirilAccount owner = "Kiril Kirov" balance = 25.0 Object Object Object Attributes (properties and fields) Operations (functions)

JavaScript Objects Overview What are Objects?

16  JavaScript is designed on a simple object-based paradigm  An object is a collection of properties  An object property is association between a name and a value  A value of property can be either  Property (variable / field)  Function (method)  Lots of predefined (native) objects available in JS  Math, document, window, etc…  Objects can be created by the developer Objects Overview

17 Objects in JS – Example var tom = { firstName: 'Tom', firstName: 'Tom', lastName: 'Miller', lastName: 'Miller', toString: function () { toString: function () { return this.firstName + " " + this.lastName; return this.firstName + " " + this.lastName; }} var kate = { firstName: 'Kate', firstName: 'Kate', lastName: 'Brown', lastName: 'Brown', toString: function () { toString: function () { return this.firstName + " " + this.lastName; return this.firstName + " " + this.lastName; }}

Objects and Properties Live Demo

Object and Primitive Types Types in JavaScript 19

20  JavaScript is a typeless language  Variables don’t have type, but their values do  JavaScript has six different types:  number, string, boolean, null, undefined and object  Object is the only Object type  It is copied by reference  number, string, boolean, null, undefined are primitive types  Copied by value Reference and Primitive Types

21  The primitive types are boolean, number, string, undefined and null  All the other types are actually of type object  Including arrays, dates, custom types, etc…  All types derive from object  Their type is object Reference and Primitive Types (2) console.log(typeof new Object() === typeof new Array()); // true console.log(typeof new Object() === typeof new Date()); // true console.log(typeof new Array() === typeof new Date()); // true

22  Primitive types are passed by value  When passed as argument  New memory is allocated  The value is copied in the new memory  The value in the new memory is passed  Primitive types are initialized with type literals  Primitive types have an object type wrapper Primitive Types var number = 5; var text = 'Hello there!';

23  Assign string values to two variables  Create an object using their value  Change the value of the variables  Each object has its own value Primitive Types – Example var fName = 'Pesho'; var lName = 'Ivanov'; var person = { firstName: fName, lastName: lName }; lName = 'Petrov'; console.log(person.lastName) // logged 'Ivanov'

Primitive and Reference Types in JS Live Demo

25  Except primitives, all other types are objects  When passed to a function, the value is not copied, but instead a reference of it is passed Object Type var marks = [ { subject : 'Java', score : 6.00 }, { subject : 'Java', score : 6.00 }, { subject : 'HTML5', score : 5.90 }, { subject : 'HTML5', score : 5.90 }, { subject : 'JavaScript', score : 6.00 }, { subject : 'JavaScript', score : 6.00 }, { subject : 'PHP', score : 6.00 }]; { subject : 'PHP', score : 6.00 }]; var student = { name: 'Deyan Dachev', marks: marks }; marks[1].score = 5.50; console.log(student.marks[1]); // logs 5.50 for HTML5 score

26  Shared object – two variables holding the same object:  Cloned objects – two variables holding separate objects: Object Cloning var peter = { name: 'Peter', age: 21 }; var maria = peter; maria.name = 'Maria'; console.log(maria); // Object {name: "Maria", age: 21} console.log(peter); // Object {name: "Maria", age: 21} var peter = { name: 'Peter', age: 21 }; var maria = JSON.parse(JSON.stringify(peter)); maria.name = 'Maria'; console.log(maria); // Object {name: "Maria", age: 21} console.log(peter); // Object {name: "Peter", age: 21}

Object Types Live Demo

JSON Objects Creating Simple objects 28

 JSON stands for JavaScript Object Notation  A data format used in JavaScript, the " prop:value " notation JSON Objects var person = { firstName: 'Dicho', firstName: 'Dicho', lastName: 'Dichov', lastName: 'Dichov', toString: function personToString() { toString: function personToString() { return this.firstName + ' ' + this.lastName; return this.firstName + ' ' + this.lastName; }}

30  JSON.stringify(obj)  Converts a JS object to JSON string:  JSON.parse(str)  Creates a JS object by JSON string: JS Object ↔ JSON String var obj = { town: 'Sofia', gps: {lat: 42.70, lng: 23.32} } var str = JSON.stringify(obj); var str = '{"town":"Sofia","gps":{"lat":42.70,"lng":23.32}}'; var obj = JSON.parse(str); // both lines below throw SyntaxError JSON.parse('{foo:"bar"}');JSON.parse("{'foo':'bar'}");

31  JSON is great, but repeating code is not, right?  Lets make several people: Building a JSON Object var dicho = {fname: 'Dicho', lname: 'Dichov', toString: function() { return this.fname + ' ' + this.lname; } toString: function() { return this.fname + ' ' + this.lname; }} var georgiev = { fname: 'Georgi', lname: 'Georgiev', toString: function() { return this.fname + ' ' + this.lname; } } var kirova = { fname: 'Maria', lname: 'Kirova', toString: function() { return this.fname + ' ' + this.lname; } }

32  A function for building JSON objects  Just pass first and last name and get an object  Something like a constructor JSON Building Function function buildPerson(fname, lname) { return { return { fname: fname, fname: fname, lname: lname, lname: lname, toString: function () { return this.fname + ' ' + this.lname; } toString: function () { return this.fname + ' ' + this.lname; } }} var dichov = buildPerson('Dicho', 'Dichov'); var georgiev = buildPerson('Georgi', 'Georgiev');

JSON Objects Live Demo

Lo-Dash

 A JavaScript utility library delivering consistency, modularity, performance & extras.  Download link What is lodash.js? 35 _.assign({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }); // → { 'a': 1, 'b': 2, 'c': 3 } _.map([1, 2, 3], function(n) { return n * 3; }); // → [3, 6, 9]

36  Lo-Dash (and it’s older cousin Underscore.js) provide functional programming library  array manipulation  collections manipulation  function customization  object creation  string manipulation  and many more… What do we use Lo-Dash for?

Lo-Dash Live Demo

38 1.Associative Arrays 2.Objects in JavaScript  Reference types  Primitive types  What is JSON? JSON   String 3.Lo-Dash Library for performance Summary

? ? ? ? ? ? ? ? ? Associative Arrays and Objects

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 40  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg