我有一个数组和两个输入。我想取第一个输入的值并将其放在变量中。我把那部分放下了。然后我想使用该变量来查找相应的数组条目并从该数组返回另一个对象。
输入为var prodNum=$('input#prodNum').val();
数组是:
var products = [
{
"brand": "brand1",
"prodNum": "01-005",
"YN": "Yes",
"Stock": "Order"
},
{
"brand": "brand2",
"prodNum": "02-005",
"YN": "Yes",
"Stock": "Ship"
},
{
"brand": "brand1",
"prodNum": "01-008",
"YN": "No",
"Stock": "Order"
}
]
我想将"YN"
值返回var YNvalue
,给定某个prodNum
例如,如果prodNum
= 01-008
,YNvalue
将为"No"
答案 0 :(得分:2)
您必须循环遍历product
数组中的对象,直到找到匹配的对象:
function getProductYN(productList, productNumber) {
for (var prodIdx = 0, prodCnt = productList.length; prodIdx < prodCnt; prodIdx++) {
if (productList[prodIdx].prodNum === productNumber)
return productList[prodIdx].YN;
}
}
var products = [{
"brand": "brand1",
"prodNum": "01-005",
"YN": "Yes",
"Stock": "Order"
},
{
"brand": "brand2",
"prodNum": "02-005",
"YN": "Yes",
"Stock": "Ship"
},
{
"brand": "brand1",
"prodNum": "01-008",
"YN": "No",
"Stock": "Order"
}
];
var prodNum = "01-008"; // $('input#prodNum').val();
var productYN = getProductYN(products, prodNum);
console.log(productYN);
&#13;
答案 1 :(得分:1)
您可以在find
数组
products
来实现
products.find(product => product.prodNum === prodNum).YN
答案 2 :(得分:1)
您可以使用以下代码。但下次再问一下试试。
var YNvalue;
for (var index = 0; index < products.length; index++) {
if (products[index].prodNum === prodNum ) {
YNvalue = products[index].YN;
break;
}
}
答案 3 :(得分:0)
如果要使用YN编号查找特定对象的YN值,在此示例中,您可以简单地遍历每个对象,直到找到具有匹配产品编号的对象。一旦我们找到该对象,我们应该返回其YN值
<html>
<head>
</head>
<body onload="main()">
<div id="results"></div>
</body>
</html>
&#13;
<?php
if(!empty($_POST['D1']) && !empty($_POST['T1'])){
$providers = array(
'google_drive' => 'https://drive.google.com/file/d/{replace}/view',
'clody' => 'https://www.cloudy.ec/embed.php?id={replace}',
'example' => 'http://example.com/log.php?id={replace}&name={replace2}&pass={replace3}'
);
if(isset($providers[$_POST['D1']])){
$url = str_replace('{replace}', $_POST['T1'], $providers[$_POST['D1']]);
echo "Your url is $url";
}
}
?>
<form method="POST" action=<?php ($_SERVER["PHP_SELF"]); ?>>
<p>chose url:
<select size="1" name="D1">
<option value="google_drive">google drive</option>
<option value="clody">clody</option>
<option value="example">example</option>
</select>
<input type="text" name="T1" size="40" value="insert code">
<input type="submit" value="go" name="B1"><input type="reset" value="reset" name="B2">
</p>
</form>
&#13;
哎呀,我有点慢了