const hasKey = (obj, keys) => {
return (
keys.length > 0 &&
keys.every(key => {
if (typeof obj !== 'object' || !obj.hasOwnProperty(key)) return false;
obj = obj[key];
return true;
})
);
};
let obj = {
a: 1,
b: { c: 4 },
'b.d': 5
};
hasKey(obj, ['a']); // true
hasKey(obj, ['b']); // true
hasKey(obj, ['b', 'c']); // true
hasKey(obj, ['b.d']); // true
hasKey(obj, ['d']); // false
hasKey(obj, ['c']); // false
hasKey(obj, ['b', 'f']); // false
const assertValidKeys = (obj, keys) =>
Object.keys(obj).every(key => keys.includes(key));
assertValidKeys({ id: 10, name: 'apple' }, ['id', 'name']); // true
assertValidKeys({ id: 10, name: 'apple' }, ['id', 'type']); // false
const symbolizeKeys = obj =>
Object.keys(obj).reduce(
(acc, key) => ({ …acc, [Symbol(key)]: obj[key] }),
{}
);
symbolizeKeys({ id: 10, name: 'apple' });
// { [Symbol(id)]: 10, [Symbol(name)]: 'apple' }
const findKeys = (obj, val) =>
Object.keys(obj).filter(key => obj[key] === val);
const ages = {
Leo: 20,
Zoey: 21,
Jane: 20,
};
findKeys(ages, 20); // [ 'Leo', 'Jane' ]
const commonKeys = (obj1, obj2) =>
Object.keys(obj1).filter(key => obj2.hasOwnProperty(key));
commonKeys({ a: 1, b: 2 }, { a: 2, c: 1 }); // ['a']
const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
const findLastKey = (obj, fn) =>
Object.keys(obj)
.reverse()
.find(key => fn(obj[key], key, obj));
findLastKey(
{
barney: { age: 36, active: true },
fred: { age: 40, active: false },
pebbles: { age: 1, active: true }
},
x => x['active']
); // 'pebbles'
const findKey = (obj, fn) =>
Object.keys(obj).find(key => fn(obj[key], key, obj));
findKey(
{
barney: { age: 36, active: true },
fred: { age: 40, active: false },
pebbles: { age: 1, active: true }
},
x => x['active']
); // 'barney'
const obj = { a: 1 };
obj.b = 2;
obj.c = 3;
// obj = { a: 1, b: 2, c: 3 }
const obj = { a: 1 };
const bKey = 'b';
obj[bKey] = 2;
obj['c'] = 3;
// obj = { a: 1, b: 2, c: 3 }
const obj = { a: 1 };
Object.assign(obj, { b: 2 }, { c: 3 });
// obj = { a: 1, b: 2, c: 3 }
const obj = { a: 1 };
Object.defineProperty(obj, 'b', {
value: 2,
enumerable: true,
configurable: true,
writable: true
});
Object.defineProperty(obj, 'c', {
value: 3,
enumerable: true,
configurable: true,
writable: true
});
// obj = { a: 1, b: 2, c: 3 }
const obj = { a: 1 };
const newObj = { …obj, b: 2, c: 3 };
// obj = { a: 1 }
// newObj = { a: 1, b: 2, c: 3 }
Массивы и объекты JavaScript
JavaScript