我试图以下面的格式循环列表(origPlan)并计算列表中每个项目的数量,然后将其转换为最终结果,如下所示:
finalPlan =[{"first":2},{"second":2}]
我的逻辑在下面但是在我的if语句中它总是返回-1并且我每次都执行我的else语句,我错过了什么?如果不包含该元素,是否有indexOf函数的替代方法将返回-1?我想我可能没有正确访问finalPlan中的项目,但我不确定如何继续。
var origPlan = {"first","second","first","second"}
var finalPlan = [];
//loop through each element of my array
for(var i =0; i<origPlan.length; i++){
//check to see if the element has been added to my new array already
if(finalPlan.indexOf(origPlan[i]) == -1){
//if not, lets add it here with quantity of 1
finalPlan.push({
variantId: origPlan[i],
quantity: 1
});
}
//other wise I will increase quantity here: logic not included for simplicity
else{console.log("duplicated");}
}
答案 0 :(得分:1)
您需要使用finalPlan
函数并检查每个对象的键。
假设finalPlan.findIndex((f) => Object.keys(f)[0] === origPlan[i]) != -1
finalPlan.findIndex((f) => Object.keys(f)[0] === origPlan[i]) === -1
^
重要:您需要检查逻辑/条件。
这是我在您的方法中所做的修复:
var origPlan = [
"first",
"second",
"third",
"fourth"
]
var finalPlan =[{"first":2},{"second":2}]
//loop through each element of my array
for (var i = 0; i < origPlan.length; i++) {
//check to see if the element has been added to my new array already
if (finalPlan.findIndex((f) => Object.keys(f)[0] === origPlan[i]) === -1) {
//if not, lets add it here with quantity of 1
finalPlan.push({
variantId: origPlan[i],
quantity: 1
});
}
//other wise I will increase quantity here: logic not included for simplicity
else {
console.log("duplicated");
}
}
console.log(finalPlan)
$response = array();
$con=mysqli_connect("localhost","root","","market");
// Check connection
if (mysqli_connect_errno())
{
die ("Failed to connect to MySQL: " . mysqli_connect_error());
}
$myData = array();
$result = mysqli_query($con, "SELECT * FROM `item`");
while ($row = mysqli_fetch_assoc($result))
{
$myData[] = $row;
}
echo json_encode($myData, JSON_UNESCAPED_UNICODE);
答案 1 :(得分:1)
事情是,{} != {}
,因为他们的引用是不同的。对于一个人来说,他们可能是同一个对象,但在内部他们引用不同的对象。
您可能想要使用一些数组函数,例如find
,map
,filter
。
对于这个例子,最好是利用Array.reduce
var origPlan = ["first", "second", "first", "second"]
var finalPlan = origPlan.reduce((acc, element) => {
if(acc[element]){
acc[element]++
}else{
acc[element] = 1
}
return acc
}, {})
console.log(finalPlan)
&#13;
答案 2 :(得分:0)
if
循环中的条件不太正确。由于你的数组finalPlan是一个复杂对象的数组,不像origPlan是一个字符串数组,你的比较总会失败并返回-1。如果是条件,请尝试以下方法:
var origPlan = ["first","second","first","second"]
var finalPlan = [];
//loop through each element of my array
for(var i =0; i<origPlan.length; i++){
//check to see if the element has been added to my new array already
if (!finalPlan.some(e => e.variantId === origPlan[i])) {
//if not, lets add it here with quantity of 1
finalPlan.push({
variantId: origPlan[i],
quantity: 1
});
}
//other wise I will increase quantity here: logic not included for simplicity
else{
console.log('duplicated');
}
}