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.
2
Answers
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
obj
object within thedata.variants
array. 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 theindex
variable.The comparison of object with
===
really won’t work, because they are different objects and you are comparing references to them. Alternatively, you can use ashallow comparison
, checking each of the properties. But comparing viaJSON.stringify
is the right and simple solution in this case, and it works. By running this code, the number0
will be displayed in the console, which is the index of the desired object.