How do you 'reverse lookup' for an object's attribute in JavaScript? For example, say I have an object:
var price = {
water: '$1.00',
beer: '$30.00',
xbox: '$500.00'
}
Typing in price.water would return '$1.00'. But what if I wanted to find out the ITEM by the PRICE, instead of the price by the item? Like I could type fnToFindItemByPrice('$1.00'), and get 'water'. Is this possible?
Thanks in advance.
You can use Object.keys and Array.find:
var price = {
water: '$1.00',
beer: '$30.00',
xbox: '$500.00'
}
function findItemByPrice(item){
return Object.keys(price).find(e => price[e] == item)
}
console.log(findItemByPrice('$1.00'))
If you have more than one property with the value, you can use Array.filter:
var price = {
water: '$1.00',
beer: '$30.00',
xbox: '$500.00',
water2: '$1.00',
}
function findItemByPrice(item){
return Object.keys(price).filter(e => price[e] == item)
}
console.log(findItemByPrice('$1.00'))
that ?
const f_reverse = obj => Object.entries(obj).reduce((r,[k,v])=>(r[v]=k,r),{})
const price =
{ water : '$1.00'
, beer : '$30.00'
, xbox : '$500.00'
}
const fruits =
{ apples : 'normandy'
, pears : 'italy'
, bananas : 'gabon'
, oranges : 'california'
}
const priceRev = f_reverse(price)
const products = f_reverse(fruits)
console.log( priceRev['$1.00'] ) // -> water
console.log( products.california ) // -> oranges
In case of multiple keys with the same value :
const f_reverse = obj => Object.entries(obj).reduce((r,[k,v])=>
{
if (!r.hasOwnProperty(v)) r[v] = k
else if (!Array.isArray(r[v])) r[v] = [ r[v], k ]
else r[v].push(k)
return r
},{})
const price =
{ water : '$1.00'
, beer : '$30.00'
, xbox : '$500.00'
, tacos : '$1.00'
, glub : '$1.00'
}
const priceRev = f_reverse(price)
console.log('$1.00->', priceRev['$1.00']) // ['water','tacos','glub']
console.log('$500.00->', priceRev['$500.00']) // 'xbox'
.as-console-wrapper {max-height: 100%!important;top:0 }
For those who always prefer to have an array back.
(in case of use by chaining plan to use a Nullish coalescing operator)
const f_reverse = obj =>
Object.entries(obj).reduce((r,[k,v])=>(r[v]??=[],r[v].push(k),r),{})
const price =
{ water : '$1.00'
, beer : '$30.00'
, xbox : '$500.00'
, tacos : '$1.00'
, glub : '$1.00'
}
const priceRev = f_reverse(price)
console.log('$1.00->', priceRev['$1.00']) // ['water','tacos','glub']
console.log('$500.00->', priceRev['$500.00']) // ['xbox']
.as-console-wrapper {max-height: 100%!important;top:0 }
Keep in mind that values are not unique, unlike keys.
var price = {
water: '$1.00',
beer: '$30.00',
coffee: '$1.00',
xbox: '$500.00'
};
var one_dollar = [];
for (let k in price) {
if (price[k] === '$1.00') {
one_dollar.push(k);
}
}
console.log(one_dollar);