通过了解其值来从对象中检索键

时间:2018-05-07 21:30:14

标签: javascript

大家好......

 var fruits = {
        "apple": "fruits/apple.png",
        "banana": "fruits/banana.png",
        "watermelon": "fruits/watermelon.jpg" 
    }
    var fruitsKeys = Object.keys(fruits);
    var fruitsValue = Object.values(fruits);

我正在寻找一种实用的方法,通过了解其值来回调对象中的键。

为了解释我为什么需要它,我想将每个值分配给一张图片,然后点击图片名称就会显示出来。

感谢您的支持



var imgHolder = document.querySelectorAll("#imageholder");
var displayedChallengeName = document.querySelector("#challengeName");
displayedChallengeName.textContent = "Challenge";

var fruits = {
		"apple": "fruits/apple.png",
		"banana": "fruits/banana.png",
		"watermelon": "fruits/watermelon.jpg",
		"grapes": "fruits/grapes.png",
		"orange": "fruits/orange.jpg",
		"mango": "fruits/mango.jpg" 
}
 
var fruitsKeys = Object.keys(fruits);
var fruitsValue = Object.values(fruits);

var displayedFruits = [];
var repeated = 0;
for(var i = 0; i<10; i++){	
		var z = fruitsValue[justRandomNum()];
		if(displayedFruits.includes(z) ){
			repeated += 1;
		}else{
			displayedFruits.push(z);
		}
	}

for(var i = 0; i<imgHolder.length; i++){
	imgHolder[i].setAttribute("src", displayedFruits[i]);

}

function challengeName(){
	randomNum = Math.floor(Math.random() * fruitsKeys.length);
	return fruitsKeys[randomNum];

}

function justRandomNum(){
	randomNum = Math.floor(Math.random() * fruitsValue.length);
	return randomNum;
}
&#13;
body { 
	background-color: #A8F2FE;
	margin: 0;
 }


#h1 {
	background-color: #F9EAA0;
	padding-bottom: 12vh;
	text-align: center;
	padding-top: 10vh;
	font-family: 'Pangolin', cursive;
	font-weight: bold;
	font-size: 50px;
	color: #223481;
	border: 6px solid #4B9AE8;
}

#h2 {
	font-family: 'Pangolin', cursive;
	font-weight: bold;
	font-size: 50px;
	color: #223481;
}

#challengeName {
	margin: 30px auto;
	font-size: 150%;
}

#holder { 
	height: 200px;
	width: 200px;
	overflow: hidden;
	position: relative;
	display: inline-block;
	margin: 0 10px;
}

.container { 
	margin: 30px auto;
}

.images {
	width: 100%;
	/*padding-bottom: 45%;*/
	position: absolute;
	display: block;
	background-color: white;
	/*right: 0;
	bottom: 0;*/
	float: left;
	/*margin: 2.5%;*/
	height: 100%;
	border: 2px solid #25336D;
	/*transition: all 0.3s;*/
	/*top: 50%;
  	left: 50%;*/
  /*	min-height: 100%;
  	min-width: 100%;*/
  /*	transform: translate(-50%, -50%);*/
}

#cont {
	margin: 20px auto;
	/*max-width: 400px;*/
}

#buttonsbar { 
	text-align: center;
	height: 40px;
 }

 #space { 
 	display: inline-block;
 	width: 5%;
  }
button { 
	text-transform: uppercase;
	height: 100%;
	width: 120px;

 }


 button:hover { 
 	color: yellow;
 	background-color: gray;
 	transition: 0.3s;
  }
&#13;
<!DOCTYPE html>
<html>
<head>
	<title>Names Game</title>
	<link rel="stylesheet" type="text/css" href="namesgame.css">
	<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
	<link href="https://fonts.googleapis.com/css?family=Pangolin" rel="stylesheet">
	<style type="text/css">
   			body { background: #A8F2FE !important; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */
	</style>
	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script> -->
</head>
<body>
	
		<h1 id="h1">Names and Pictures Game
			<br>
			<br>
			<span id="challengeName">MANGO</span>
		</h1>	


	<div id="buttonsbar">
		<button class="rounded">Start</button>
		<span id="space"></span>
		<button class="rounded" >Reset</button>
	</div>
	

	<div class="container">
		<div class="row d-flex justify-content-center">
			<div >
				<div id="holder" ><img id="imageholder" class="images" src=""></div>
				<div id="holder" ><img id="imageholder" class="images" src=""></div>
			</div>
			<div >
				<div id="holder" ><img id="imageholder" class="images" src=""></div>
				<div id="holder" ><img id="imageholder" class="images" src=""></div>
			</div>
		</div>	
	</div>
</body>
</html>
© 2018 GitHub, Inc.
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以使用Map创建Object.entries()个值,并使用Array.map()切换键和值:

&#13;
&#13;
const fruits = {
  "apple": "fruits/apple.png",
  "banana": "fruits/banana.png",
  "watermelon": "fruits/watermelon.jpg"
}

const valuesToKeys = new Map(Object.entries(fruits).map(([k, v]) => [v, k]));

console.log(valuesToKeys.get('fruits/apple.png'));
&#13;
&#13;
&#13;

另一种选择是使用Object.keys()Array.reduce()创建一个具有切换键和值的对象:

&#13;
&#13;
const fruits = {
  "apple": "fruits/apple.png",
  "banana": "fruits/banana.png",
  "watermelon": "fruits/watermelon.jpg"
};

const fruitsByValues = Object.keys(fruits)
  .reduce((r, k) => {
    r[fruits[k]] = k;
  
    return r;
  }, {});
  
console.log(fruitsByValues['fruits/watermelon.jpg']);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用Object.keys获取密钥,然后使用Array.find查找与该值相关联的密钥。

&#13;
&#13;
const fruits = {
  "apple": "fruits/apple.png",
  "banana": "fruits/banana.png",
  "watermelon": "fruits/watermelon.jpg"
}

function getKeyByValue(obj, value) {
  return Object.keys(obj).find(key => obj[key] === value)
}

console.log(getKeyByValue(fruits, 'fruits/apple.png'));
&#13;
&#13;
&#13;