I need to compare and manipulate JSON objects.
First object
let data1 = {
"id": "111",
"entity_id": "222",
"text_id": "333",
"details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving"
}]
}
Second object
let data2 = [{
"id": "111",
"text_id": "333",
"criteria_type": "TXT",
"value": 1000,
"comp": {
"id": "444",
"name": "driving"
}
}, {
"id": "222",
"text_id": "444",
"criteria_type": "TXT",
"value": 2000,
"comp": {
"id": "555",
"name": "swiming"
}
}]
There are 2 objects data1
and data2
. Here, I need to compare the data1.details
array with the data2
array key => data1.details.comp_id
with data2.comp.id
if not match then I need to push value
, id
and name
to data1
object. Please help me to resolve this issue.
Resulting object
data1
will be:
{
"id": "111",
"entity_id": "222",
"text_id": "333",
"declaration_details": [{
"value": 1000,
"comp_id": "444",
"CompName": "driving",
}, {
"value": 2000,
"comp_id": "555",
"CompName": "swiming",
}]
}
3
Answers
You can use JSON.stringify(yourJsonObject) to convert your objects to strings.
Then you can compare them like this.
areEqual = string1 == string2
. Make sure the object properties are in the same order for both objects.Use
filter()
to find objects in thedata2
matchingcomp.id
. Then you can just usemap()
to create a new array. Finally, you can add themappedData2
array to thedata1
indeclaration_details
.Based on your expected result, wouldn’t you just need to map
data2
to thedeclaration_details
of the resulting object?