Home > Blockchain >  How to 'reverse search' for a property in an object in JavaScript
How to 'reverse search' for a property in an object in JavaScript

Time:01-14

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.

CodePudding user response:

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);

CodePudding user response:

You can achieve this by using Object.entries() and a for ... of loop. Your code would look like this:

const price = {
    water: '$1.00',
    beer: '$30.00',
    xbox: '$500.00'
}

for (const [key, value] of Object.entries(price)) {
    if (value === '$1.00') {
        console.log(key);
    }
}

If you are going to have more than 1 value with $1.00 like @mister wtf said, then you have to use Array.push to get this. See an example of this below:

let results = [];
let result;
const price = {
    water: '$1.00',
    sparklingWater: '$1.00',
    beer: '$30.00',
    xbox: '$500.00'
}

for (const [key, value] of Object.entries(price)) {
    if (value === '$1.00') {
        results.push(key);
    }
}

if (results.length < 2) {
    result = results[0];
} else {
    result = results;
}

console.log(result);

Hoped this helped!

CodePudding user response:

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'))

  •  Tags:  
  • Related