I have a data
var data = {
"variants": [{
"quantity": "20",
"varientId": 8,
"currency": "YEN",
"extraField": {
"Size": "10",
"Color": "Red",
"Material": "Denim"
},
"price": "199"
},
{
"quantity": "15",
"varientId": 10,
"currency": "YEN",
"extraField": {
"Size": "9",
"Color": "Red",
"Material": "Denim"
},
"price": "249"
},
{
"quantity": "18",
"varientId": 12,
"currency": "YEN",
"extraField": {
"Size": "8",
"Color": "Green",
"Material": "Rubber",
},
"price": "279"
}
]
}
and an object :
var obj = {
"Size": "10",
"Color": "Red",
"Material": "Denim"
}
I've tried this
var index = null
for(var l = 0; l<data.variants.length; l++){
if(data.variants[l].extraField === obj){
index = l
}
}
console.log(index)
I've also tried using JSON.stringify:
JSON.stringify(data.variants[l].extraField) === JSON.stringify(obj)
I'm getting null when console logging the index variable but I should be getting 0 since the obj object matches the first variant's extrafield.
The reason your current approach is not working is that you are trying to compare two objects directly using
===, which will not work for objects. In JavaScript, objects are compared by reference, not by their content, so even if two objects have the same key-value pairs, they will not be considered equal unless they are the same object in memory.To find the index of the matching object in the array, you can use the
JSON.stringify()method to compare the stringified versions of the objects. However, there is a more efficient and straightforward solution using a loop and comparing individual properties. Here's the easiest solution for your problem:This code will correctly find the index of the first object that matches the properties of the
objobject within thedata.variantsarray. It loops through each variant, compares the properties one by one, and breaks out of the loop as soon as it finds a matching variant, assigning the index to theindexvariable.