Object Tips
Access the values of an object from within another object
We can use the value from an object as a reference to another object. In the next example we use 3 objects. The first contains data about our kitchen (door open of closed and temperature) and the second object contains data about the living room (lamp on or of and temperature). The third object only contains functions that collect the data from the first two objects.
var kitobj =
{
door: "closed",
temp: "22",
};
var livingobj =
{
lamp: "off",
temp: "24",
};
var houseobj =
{
getkitchen()
{
return "The door is "+kitobj.door + " the temperature is " + kitobj.temp
},
getliving()
{
return "The lamp is "+livingobj.lamp + " the temperature is " + livingobj.temp
}
};
alert(houseobj.getkitchen());
alert(houseobj.getliving());
The practical use is that we can have dedicated objects for every room in our house which we only have to change when one value changes.
Add an element to an object
Adding an element to an object is simple. Just add a new key-value set.
var author =
{
name : "Luc Volders",
languages : ["C++", "Javascript", "Lua", "Python"]
}
We can add an element to this objevct in two ways that both achieve the same:
author.booktitle = "Javascript tips"
or
author["booktitle"] = "Javascript tips"
Make sure, if you use the second method, to use a string as the key.
Adding an element to an object is simple. Just add a new key-value set.
var author =
{
name : "Luc Volders",
languages : ["C++", "Javascript", "Lua", "Python"]
}
We can add an element to this objevct in two ways that both achieve the same:
author.booktitle = "Javascript tips"
or
author["booktitle"] = "Javascript tips"
Make sure, if you use the second method, to use a string as the key.
Add properties of an object to another object
There are two objects echt with different properties. The next snippet shows how to merge the objects into the first object without overwriting the properties and values from the first object.
var object01 = {key1: "C++", key2: "Javascript", key3: "Lua"}
var object02 = {key2: "Javascript", key3: "Lua", key4: "Python"}
function mergeobject(object01, object02) {
for (var key2 in object02) {
if (object02.hasOwnProperty(key2) && !object01.hasOwnProperty(key2)) {
object01[key2] = object02[key2];
}
}
return object01;
}
alert(JSON.stringify(mergeobject(object01,object02)))
De alert zal het volgende weergeven:
Object { key1: "C++", key2: "Javascript", key3: "Lua", key4: "Python" }
There are two objects echt with different properties. The next snippet shows how to merge the objects into the first object without overwriting the properties and values from the first object.
var object01 = {key1: "C++", key2: "Javascript", key3: "Lua"}
var object02 = {key2: "Javascript", key3: "Lua", key4: "Python"}
function mergeobject(object01, object02) {
for (var key2 in object02) {
if (object02.hasOwnProperty(key2) && !object01.hasOwnProperty(key2)) {
object01[key2] = object02[key2];
}
}
return object01;
}
alert(JSON.stringify(mergeobject(object01,object02)))
De alert zal het volgende weergeven:
Object { key1: "C++", key2: "Javascript", key3: "Lua", key4: "Python" }
Be carefull when combining objects
It is possible to combine multiple objects into one large object. You can do that with the spread operator. Just take care that all key elements must be unique otherwise they will be overwritten. The next snippet demonstrates this.
var object1 = {'a': 1, 'b': 2, 'c': 5};
var object2 = {'c': 3};
var object3 = {'d': 4};
const total = {...object1, ...object2, ...object3};
total now contains: { a: 1, b: 2, c: 3, d: 4 }
As you can see the value of element "c" from the first obeject is overwritten by the element "c" in the second object.
Calculate the average value in an array with objects
There is a certain value in an array with objects of which we want to know the average. Start with iterating through the array and get the value out of each object and add these. Then divide that figure by the length of the array.
var average = 0;
var total = 0;
var temps = [
{
month: 'Jan',
temp: 5
}, {
month: 'Feb',
temp: 9
}, {
month: 'Mar',
temp: 12
}, {
month: 'Apr',
temp: 15
}, {
month: 'May',
temp: 19
}
]
for (i=0; i<temps.length; i++)
{
total = total + temps[i].temp;
}
average = total / temps.length;
alert(average);
Convert an array to an object
The next snippet shows how to convert an array into an object.
const names = ['C++', 'Javascript', 'Lua', 'Python'];
const namesobj = Object.assign({}, names);
console.log(namesobj);
The next snippet shows how to convert an array into an object.
const names = ['C++', 'Javascript', 'Lua', 'Python'];
const namesobj = Object.assign({}, names);
console.log(namesobj);
Convert an array with paired elements to an object
There is an array in which the elements are strings with pairs of data. The pairs are separated by a special character. The example has elements in the array like "author-Luc Volders" To convert this array into an object we can use the following method:
- Start with declaring an empty object
- Get the length of the array
- Make a loop for which iterates over the length
- Use destructuring with the split command to separate the strings
- Put the string pairs into the object.
Here is the code that achieves that:
const bookarray = ["author-Luc Volders", "Title-ESP32 Simplified", "Language-English", "pages-384"];
var bookobject= {};
for (var i=0; i<bookarray.length; i++)
{
var [key, value] = bookarray[i].split("-");
bookobject [key]=value;
};
console.log(bookobject);
Convert an array with objects to an array
This tip shows the reverse action from the previous one. There is an array with objects and we want it converted to an array.
temperatures=
[
{ month:"jan",temp:34},
{ month:"feb",temp:89}
]
var temparray = [];
for (var i = 0; i < temperatures.length; i++) {
temparray.push((temperatures[i].month)+":"+temperatures[i].temp);
}
alert(temparray);
The alert will show: jan:34,feb:89
Convert an object to an array
Using Object.values(object1) we can convert an object to an array. Here is an example.
const testobj =
{
a: 'Javascript',
b: 42,
c: false
};
testarray=(Object.values(testobj));
alert(testarray)
The alert shows an array with only the values from the object.
testarray=(Object.keys(testobj));
alert(testarray)
This time the alert shows the array with the keys of the object.
testarray=(Object.entries(testobj));
alert(testarray)
And now the alert shows the array that contains the pairs of the keys with the objects. Each pair is placed in a seperate subarray.
Using Object.values(object1) we can convert an object to an array. Here is an example.
const testobj =
{
a: 'Javascript',
b: 42,
c: false
};
testarray=(Object.values(testobj));
alert(testarray)
The alert shows an array with only the values from the object.
testarray=(Object.keys(testobj));
alert(testarray)
This time the alert shows the array with the keys of the object.
testarray=(Object.entries(testobj));
alert(testarray)
And now the alert shows the array that contains the pairs of the keys with the objects. Each pair is placed in a seperate subarray.
Copy an object
You can use the spread operator to copy an object like this:
var author = {
name: "Luc",
book1: "ESP32 Simplified",
book2: "Javascript tips"
};
var authorcopy = {...author};
console.log(authorcopy)
You can use the spread operator to copy an object like this:
var author = {
name: "Luc",
book1: "ESP32 Simplified",
book2: "Javascript tips"
};
var authorcopy = {...author};
console.log(authorcopy)
Get the highest value out of an object
If you need to distill the highest value out of an object you can do that with the next snippet.
var scores =
{
"C++": 7,
"Javascript": 9,
"Lua": 8,
"Python": 8
}
function best(searchobj)
{
var keys = Object.keys(searchobj);
var max = 0;
for(var i = 0; i < keys.length; i++)
{
if(searchobj[keys[i]] >= max)
{
max = (searchobj[keys[i]]);
};
};
return "Highest = "+max;
};
alert(best(scores));
Get the maximum value out of an array with objects
The next snippet shows how to get a maximum value out of an array with objects using the map() function.
const measurements = [
{
"room": "Mancave",
"temp": 15
},
{
"room": "Kitchen",
"temp": 22
},
{
"room": "Living",
"temp": 20
}
]
const maxtemp = Math.max(...measurements.map(m => m.temp))
console.log(maxtemp)
The next snippet shows how to get a maximum value out of an array with objects using the map() function.
const measurements = [
{
"room": "Mancave",
"temp": 15
},
{
"room": "Kitchen",
"temp": 22
},
{
"room": "Living",
"temp": 20
}
]
const maxtemp = Math.max(...measurements.map(m => m.temp))
console.log(maxtemp)
Get the number of keys of an object
If you need to know how many elemets there are in an object you just have to know the number of the keys. Here is how you can find that number.
var language = {id: 1, name: 'Javascript'}
test = Object.keys(language).length;
alert(test)
If you need to know how many elemets there are in an object you just have to know the number of the keys. Here is how you can find that number.
var language = {id: 1, name: 'Javascript'}
test = Object.keys(language).length;
alert(test)
Get objects out of an array with objects
Using destructuring you can get the individual objects out of an array with objects.
var rooms = [{name:"Kitchen"}, {name:"Mancave"}, {name:"Living"}];
var [first,second] = rooms;
console.log(first);
console.log(second.name);
Both variables first and second will contain one of the array objects.
Using destructuring you can get the individual objects out of an array with objects.
var rooms = [{name:"Kitchen"}, {name:"Mancave"}, {name:"Living"}];
var [first,second] = rooms;
console.log(first);
console.log(second.name);
Both variables first and second will contain one of the array objects.
Get relevant info out of a JSON object
A JSON object is in reality just a Javascript object. JSON objects are often used in IOT projects to send information from a micro-controller to a computer. In this example there is a JSON object where only information about the doors in our house is shown. The key doors contains an array that has information about several doors in our house being open or closed. The next snippet shows how to get relevant information out of the object and create a string that only shows which doors are open.
var alarmdoors = "";
home =
{
"doors":
[{
name: "kitchen",
state: "open"
},
{
name: "living",
state: "open"
},
{
name: "garage",
state: "closed"
},
{
name: "attick",
state: "closed"
}]
}
for(var i=0; i<home.doors.length; i++)
{
if (home.doors[i].state == "open")
{
alarmdoors = alarmdoors + home.doors[i].name + " , ";
}
}
alarmdoors = "The following doors are open " + alarmdoors
alert (alarmdoors)
A JSON object is in reality just a Javascript object. JSON objects are often used in IOT projects to send information from a micro-controller to a computer. In this example there is a JSON object where only information about the doors in our house is shown. The key doors contains an array that has information about several doors in our house being open or closed. The next snippet shows how to get relevant information out of the object and create a string that only shows which doors are open.
var alarmdoors = "";
home =
{
"doors":
[{
name: "kitchen",
state: "open"
},
{
name: "living",
state: "open"
},
{
name: "garage",
state: "closed"
},
{
name: "attick",
state: "closed"
}]
}
for(var i=0; i<home.doors.length; i++)
{
if (home.doors[i].state == "open")
{
alarmdoors = alarmdoors + home.doors[i].name + " , ";
}
}
alarmdoors = "The following doors are open " + alarmdoors
alert (alarmdoors)
Get the values of an object out of an array with objects
If we need the data from an object that is part of an array with objects we can do that with the following snippet. The snippet puts the data into a new array.
books =
[
{
"Author": "Luc Volders",
"Bookname": "ESP32 Simplified",
"Year published": "2020",
"Language": "english",
"Printer": "Lulu"
},
{
"Author": "Luc Volders",
"Bookname": "Javascript tips",
"Year published": "2021",
"Language": "english",
"Printer": "Lulu"
}
]
function bookvalues(fromarray)
{
var keys = Object.keys(fromarray);
var result = [];
for(var i = 0; i < keys.length; i++)
{
result.push(fromarray[keys[i]]);
};
return result;
};
alert(bookvalues(books[1]));
The alert will show all the data from book 2. They will be in the array with the name result.
If we need the data from an object that is part of an array with objects we can do that with the following snippet. The snippet puts the data into a new array.
books =
[
{
"Author": "Luc Volders",
"Bookname": "ESP32 Simplified",
"Year published": "2020",
"Language": "english",
"Printer": "Lulu"
},
{
"Author": "Luc Volders",
"Bookname": "Javascript tips",
"Year published": "2021",
"Language": "english",
"Printer": "Lulu"
}
]
function bookvalues(fromarray)
{
var keys = Object.keys(fromarray);
var result = [];
for(var i = 0; i < keys.length; i++)
{
result.push(fromarray[keys[i]]);
};
return result;
};
alert(bookvalues(books[1]));
The alert will show all the data from book 2. They will be in the array with the name result.
Get the values or keys from an object out of an array
The previous tip (Get the values of an object out of an array with objects) showed how to get the values of an object out of an array. That method gives you flexibility. You can do this also with one line of code.
books =
[
{
"Author": "Luc Volders",
"Bookname": "ESP32 Simplified",
"Year published": "2020",
"Language": "english",
"Printer": "Lulu"
},
{
"Author": "Luc Volders",
"Bookname": "Javascript tips",
"Year published": "2020",
"Language": "english",
"Printer": "Lulu"
}
]
var result = Object.values(books[1]);
alert(result);
The above snippet gives you all the data from an object (book 2).
To get the keys of that object in stead of the values use the next snippet:
var result = Object.keys(books[1]);
alert(result);
Get values out of an object with arrays
If you need to get a value out of an object that is filled with arrays you can do that as follows:
var languages =
{
oldlang: ["Algol", "Cobol", "Forth"],
newlang: ["Javascript", "Lua", "Python"]
};
alert("Old language is "+languages.oldlang[1]);
alert("New language is "+languages.newlang[0]);
If you need to get a value out of an object that is filled with arrays you can do that as follows:
var languages =
{
oldlang: ["Algol", "Cobol", "Forth"],
newlang: ["Javascript", "Lua", "Python"]
};
alert("Old language is "+languages.oldlang[1]);
alert("New language is "+languages.newlang[0]);
How many keys are there in an object
To know how many keys there are in an object I show you two methods.
var numkeys = Object.keys(myobj).length
The second method counts the number of keys in a for-loop:
var numkeys = 0;
for (let k in myobj) if (myobj.hasOwnProperty(k)) numkeys++;
To know how many keys there are in an object I show you two methods.
var numkeys = Object.keys(myobj).length
The second method counts the number of keys in a for-loop:
var numkeys = 0;
for (let k in myobj) if (myobj.hasOwnProperty(k)) numkeys++;
How to change the property of a nested Object
The easiest way to change a property of a nested object is to use the dot notation. The second method is the bracket notation. I will show you both here.
Imagine a home automation system in which each room has an object with its properties.
var room;
var lampstate;
room = {
"name" : "mancave",
"temperature" : 20,
"doorsensor" : "off",
"lamps" : {
"ceiling" : "on",
"wall1" : "off"
}
}
If we want to know if the lamp on the wall is on or off we can retrieve that info as follows:
lampstate = room.lamps.wall1;
alert(lampstate);
With this dot notation we can also change the state of the lamp in an easy way:
room.lamps.wall1 = "on";
lampstate = room.lamps.wall1;
alert(lampstate);
To achieve this with the bracket notation use the following code:
lampstate = room["lamps"]["wall1"];
alert(lampstate);
room["lamps"]["wall1"] = "onn";
lampstatus = room["lamps"]["wall1"];
alert(lampstate);
Iterate over an object
The easiest way to ieterate over an object is with a for-loop. In this example both they keys and their values are printed.
var object = {'a': 1, 'b': 2, 'c' : 3};
for (key in object)
{
alert(key+" : "+object[key]);
}
The easiest way to ieterate over an object is with a for-loop. In this example both they keys and their values are printed.
var object = {'a': 1, 'b': 2, 'c' : 3};
for (key in object)
{
alert(key+" : "+object[key]);
}
Merge multiple objects into one
It is possible to merge multiple objects into one larger object. Double entries will be omitted. Here is an example from an IOT project in which the information from multiple rooms is combined to one large object representing the house.
var kitchen = { lamp: "on", door: "open" };
var living = { temperature: "24", tablelamp: "off" };
var garage = { lights: "off", gate: "closed"};
var home = Object.assign(kitchen,living,garage);
alert(JSON.stringify(home));
Merge multiple objects into one 2
Another method to merge multiple objects into one is by using the spread operator. Here also double entries are omitted. Here again is an example from an IOT project in which the information from multiple rooms is combined to one large object representing the house.
var kitchen = { lamp: "on", door: "open" };
var living = { temperature: "24", tablelamp: "off" };
var garage = { lights: "off", gate: "closed"};
var home = {...kitchen, ...living, ...garage};
alert(JSON.stringify(home));
Pretty print objects
Pretty print is a not widely known option in the JSON.stringify() command. It's purpose is to make objects look good. Here is an example.
var kitchen = { lamp: 'on', door: 'closed', temperature: '22' };
alert(JSON.stringify(kitchen, null, 4));
The reult looks like this:
{
"lamp": "on",
"door": "closed",
"temperature": "22"
}
This only works with alert() and in the console. It will not work with document.write.
The last parameter in the command (4 in this example) determines the amount of spaces to be used as an indent.
Remove a function from an object
Just like in variables and in arrays we can put a function into an object. If you need to remove it first convert the object to a string with JSON.stringify() and then convert it back with JSON.parse().
var room = { lamp: "on", action: function() {alert("lamp on");},
temperature: "24" };
room.action();
var room = JSON.stringify(room);
var room = JSON.parse(room);
alert(JSON.stringify(room));
In this example the function is executed once before it is removed.
Remove a key and value from an object
To remove a key and its value from an object just use delete as the next snippet demonstrates.
var home =
{
room: "attick",
temp: 20,
humidity: 50
};
delete home.humidity
alert(JSON.stringify(home))
Remove duplicates from an array with objects
Here is an example that shows how to remove duplicates from an array with objects.
let rooms = [
{name: "cellar"},
{name: "mancave"},
{name: "mancave"},
{name: "kitchen"},
{name: "attick"}
];
const data = Array.from(new Set(rooms.map(JSON.stringify))).map(JSON.parse);
alert(JSON.stringify(data));
console.log(data)
Here is an example that shows how to remove duplicates from an array with objects.
let rooms = [
{name: "cellar"},
{name: "mancave"},
{name: "mancave"},
{name: "kitchen"},
{name: "attick"}
];
const data = Array.from(new Set(rooms.map(JSON.stringify))).map(JSON.parse);
alert(JSON.stringify(data));
console.log(data)
Sort an array of objects on a key
To sort an array with objects we can use the generally used sort function:
var sortfunc = arr => {
arr.sort((a, b) => {
return a-b;
});
};
What we need to do is to replace a and b by the key name of the object. The next example shows how to sort an array with objects that contain information about room temperature.
const home = [
{
room: "attick",
temp: 20
},
{
room: "garage",
temp: 15
},
{
room: "living",
temp: 22
},
];
var sorttemp = arr =>
{
arr.sort((a, b) =>
{
return a.temp - b.temp;
});
};
sorttemp(home);
document.write(JSON.stringify(home));
Store objects in localstorage
You can only store strings in localstorage. If you need to store an object first convert it to a string like this:
var myobject = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('myobject', JSON.stringify(myobject));
To retrieve the object use:
var myobject = localStorage.getItem('myobject');
myobject=JSON.parse(myobject)
to show the object use:
alert('myobject: '+ JSON.stringify(myobject));
You can only store strings in localstorage. If you need to store an object first convert it to a string like this:
var myobject = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('myobject', JSON.stringify(myobject));
To retrieve the object use:
var myobject = localStorage.getItem('myobject');
myobject=JSON.parse(myobject)
to show the object use:
alert('myobject: '+ JSON.stringify(myobject));
Test if a key exists
If you are doing an IOT project you might have an object in which temperetaure values are stored. They might get stored later on in the program. And it may happen dat you need to know at a certain point if the temperature you want to check already has been registered. This is how you can check that.
var temperature={"kitchen":20,"living":22}
kitavail = temperature.hasOwnProperty("kitchen");
manavail= temperature.hasOwnProperty("mancave");
alert(kitavail)
alert(manavail)
If you are doing an IOT project you might have an object in which temperetaure values are stored. They might get stored later on in the program. And it may happen dat you need to know at a certain point if the temperature you want to check already has been registered. This is how you can check that.
var temperature={"kitchen":20,"living":22}
kitavail = temperature.hasOwnProperty("kitchen");
manavail= temperature.hasOwnProperty("mancave");
alert(kitavail)
alert(manavail)
Test if an element exists in an array with objects
To check if an element exists in an arry with objects you can use the next snippet.
var array = [
{ id: 1, room: 'Mancave' },
{ id: 2, room: 'Kitchen'},
{ id: 3, room: 'Cellar' }];
function roomexists(room) {
return array.some(function(el) {
return el.room === room;
});
}
console.log(roomexists('Kitchen'));
console.log(roomexists('Attick'));
To check if an element exists in an arry with objects you can use the next snippet.
var array = [
{ id: 1, room: 'Mancave' },
{ id: 2, room: 'Kitchen'},
{ id: 3, room: 'Cellar' }];
function roomexists(room) {
return array.some(function(el) {
return el.room === room;
});
}
console.log(roomexists('Kitchen'));
console.log(roomexists('Attick'));
Test if an object is empty
It is easy to test if an object is empty. Just test if the length of the keys is zero. Here is an example that demonstrates this.
var language = {id: 1, name: 'Javascript'}
test = Object.keys(language).length === 0;
alert(test)
It is easy to test if an object is empty. Just test if the length of the keys is zero. Here is an example that demonstrates this.
var language = {id: 1, name: 'Javascript'}
test = Object.keys(language).length === 0;
alert(test)
Test wether two objects are fully identical
We can not use == or === to compare two objects. It is possible to compare them by first converting them to a string. The following example shows how it is done.
var obj1 = {Room: "mancave", sensor: 'lamp', status: "on" };
var obj2 = {Room: "mancave", sensor: 'lamp', status: "on" };
alert(JSON.stringify(obj1) === JSON.stringify(obj2));
The slightest variation like a capital letter or a mix up of the elements will have the alert show "false".