If you know the index, check if the index contains the value, and if not, check if it's empty:
const has = (obj, index, value) => obj[index] === 71 || !Object.keys(obj).length;
const index = 2;
const value = 71;
console.log('empty: ', has({}, index, value));
console.log('contains 71: ', has({ 1: 13}, index, value));
console.log('contains 71: ', has({ 1: 13, 2: 71 }, index, value));
If you don't know the index, you can use Object#keys to extract the keys, check if length is 0 (!values.length), and if not use Array#findIndex to see the object contains the request value:
const facets = { 1: 0, 2: 71 };
const has = (obj, value) => {
const keys = Object.keys(obj);
return !keys.length || keys.findIndex((key) => obj[key] === value) !== -1;
}
const value = 71;
console.log('empty: ', has({}, value));
console.log('contains 71: ', has({ 1: 13}, value));
console.log('contains 71: ', has({ 1: 13, 2: 71 }, value));
Another option when the index is unknown is to use Object#values.
Note: Object#values is not part of ECMAScript2015 (ES6), but a draft in ECMAScript2017, and is supported only by Chrome and Firefox.
Use Object#values to extract the values, check if length is 0 (!values.length), and if not use Array#includes to see if values contain the request value.
const facets = { 1: 0, 2: 71 };
const has = (obj, value) => {
const values = Object.values(obj);
return !values.length || values.includes(value);
}
const value = 71;
console.log('empty: ', has({}, value));
console.log('contains 71: ', has({ 1: 13}, value));
console.log('contains 71: ', has({ 1: 13, 2: 71 }, value));
return Object.keys(facets).length == 0 || facets[index] === 71;?