Object
A value constructed with new
unless using array, object, or regexp literal notation. Objects are always referred to by variables with a reference.
Remember
- keys are converted to strings
if (obj.foo)
checks truthiness, not membership- reading a missing key evaluates to
undefined
- when possible,
obj.foo
is preferred toobj['foo']
- similarly,
{ a: 1 }
is preferred to{ 'a': 1 }
Construction
const obj = {};
obj;
{}
const obj = {
foo: 'hello',
bar: 'world'
};
obj;
{ foo: 'hello', bar: 'world' }
Get
const object = { foo: 1 };
object.foo;
1
const key = 'foo';
object[key];
1
object.missing;
undefined
Set
Keys are strings
Keys are converted to strings.
const object = {};
object[1] = 'number';
object['1'] = 'string';
object;
{ '1': 'string' }
const object = {};
object.a = 1;
object['b'] = 2;
object;
{ a: 1, b: 2 }
Remove
const object = { a: 1, b: 2 };
delete object.a;
object;
{ b: 2 }
delete object['b'];
{}
Check Membership
Falsey values vs key existence
Do you want to check if an object has a key, or that key's value is truthy?
const obj = { foo: 0 };
if (obj.foo) console.log('will not run');
if ('foo' in obj) console.log('will run');
'will run'
const object = { foo: 'bar' };
'foo' in object
true
object.hasOwnProperty('foo');
true
Iterating
const object = {
a: 'one',
b: 'two',
c: 'three'
};
Object.keys(object);
['a', 'b', 'c']
Object.values(object);
['one', 'two', 'three']
Object.entries(object);
[
['a', 'one'],
['b', 'two'],
['c', 'three']
]
for (const key of Object.keys(object)) {
console.log(key);
}
'a'
'b'
'c'
Examples
const foodPrices = {
taco: 3,
burrito: 8
};
const prices = {
...foodPrices,
water: 20
};
prices.water = 0;
function getPrice(item) {
if (item in prices) {
return `we do not sell ${item}`;
} else {
return `${item}: ${prices[item]} dollars`;
}
}
getPrice('taco');
'taco: 3 dollars'
getPrice('water');
'water: 0 dollars'
getPrice('fries');
'we do not sell fries'
const arr = [1, '1', 2];
cosnt counts = {};
for (const el of arr) {
counts[el] = (counts[el] || 0) + 1;
}
counts;
{ '1': 2, '2': 1 }
const object = {
};