如何在 JavaScript 中“反向搜索”对象中的属性

问题描述 投票:0回答:4

如何在 JavaScript 中“反向查找”对象的属性?

例如,假设我有一个对象:

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

输入

price.water
将返回
'$1.00'
。但如果我想通过 PRICE 找到 ITEM,而不是按商品的价格,我也想输入
fnToFindItemByPrice('$1.00')
,然后得到
'water'

javascript object reverse
4个回答
3
投票

您可以使用

Object.keys
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'))

如果您有多个具有该值的属性,您可以使用

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


1
投票

请记住,与键不同,值不是唯一的。

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


1
投票

您可以通过使用

Object.entries()
for ... of
循环来实现此目的。你的代码看起来像这样:

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

如果您要使用

$1.00
获得超过 1 个值,就像 @mister wtf 所说的那样,那么您必须使用
Array.push
来获取此值。请参阅下面的示例:

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

希望这有帮助!


1
投票

那个?

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

如果多个键具有相同的值:

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 }

对于那些总是喜欢拥有阵列的人。
(如果通过链接计划使用空合并运算符

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 }

© www.soinside.com 2019 - 2024. All rights reserved.