Skip to content

Instantly share code, notes, and snippets.

@eveningkid
Created January 23, 2020 10:12
Show Gist options
  • Save eveningkid/35e5f4f951bf97d8a337fda22b164a24 to your computer and use it in GitHub Desktop.
Save eveningkid/35e5f4f951bf97d8a337fda22b164a24 to your computer and use it in GitHub Desktop.
// Grouped data can be structured in two different ways:
// - as a list:
const chris = [
'Christine',
'?',
'Ireland',
];
console.log(chris[0]);
// - as an object:
const chris = {
country: 'Ireland',
name: 'Christine',
age: '?',
};
console.log(chris.name);
// Both work, yet using an object let us reuse
// a similar pattern/schema for any similar data
// e.g. another person
// == How to get a value from an object?
// 1. Dot notation
console.log(chris.age);
// 2. Squared brackets
// Difference is, what's inside the brackets will
// be evaluated first, then translated to "object.property"
console.log(chris['age']);
// DON'T DO THAT, it's just for the sake
// of the example!!
console.log(chris['a' + 'g' + 'e']);
// You can definitely use variables as key/property names
const keyName = 'age';
console.log(chris[keyName]);
// == Looping through objects
for (let property in chris) {
// First, property = 'name'
// Then, property = 'age', ...
// `chris[property]` refers to the property value
console.log(
'Property:', property,
'Value:', chris[property]
);
}
// == How to add properties?
const marek = {};
marek.age = 100;
marek.name = 'Marek';
// You can change a property later on, even if
// it's been defined previously.
// We are also using the squared brackets notation
// here
marek['age'] = 200;
// == How to delete a property?
// Use the `delete` keyword, followed by the object
// property you want to remove
delete marek.age;
delete marek['age'];
// == How to check if an object has a property?
// 1. 'propertyName' in object
if ('age' in marek) {
console.log('I know your age');
}
// 2. `object.hasOwnProperty(propertyName)`
if (marek.hasOwnProperty('age')) {
console.log('I know your age');
}
// == Handy methods
// To get an object's keys' list, we'd do the following:
const listOfKeys = [];
for (let property in chris) {
listOfKeys.push(property);
}
// ...which takes 4 lines of code...let's do it in one:
Object.keys(chris) => ['age', 'name', 'country'];
// `Object.values` works the same, but with an object's values
Object.values(chris) => ['Christine', ...]
// `Object.entries` returns a list of "couples" of data:
// [[keyName, keyValue], ...]
Object.entries(chris) => [
['name', 'Christine'],
['age', '?'],
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment