I'm struggling to find a solution for merging two JSON objects. Despite searching for answers, I haven't found any that have been helpful. My goal is to compare two objects and if there's a match, add an attribute as a marker to the first object. Here's an example:
Fiddle: https://jsfiddle.net/aunzyfcj/
First input object:
var firstInput = [{
"id": "43",
"published": "yes",
"publish_date": "20.08.2019"
}, {
"id": "44",
"published": "yes",
"publish_date": "20.08.2019"
}]
Second input object:
var secondInput = [{
"id": 92,
"id_artikla": "140"
}, {
"id": 93,
"id_artikla": "139"
}, {
"id": 94,
"id_artikla": "44"
}, {
"id": 95,
"id_artikla": "10"
}, {
"id": 96,
"id_artikla": "12"
}, {
"id": 97,
"id_artikla": "22"
}, {
"id": 98,
"id_artikla": "9"
}]
I want to check if the "id": "44"
from the firstInput
object exists in the "list" of the secondInput
object and create a third output
object with a copy of (same length) the firstInput
, but this time adding the attribute "status": "SAVED"
if the "id": "44"
exists in secondInput
as "id_artikla": "44"
.
If there's no match, I'd like to add the attribute "status": "SAVE_ME"
.
Please see the output example below.
Output object:
var output = [{
"id": "43",
"published": "yes",
"publish_date": "20.08.2019",
"status": "SAVE_ME"
}, {
"id": "44",
"published": "yes",
"publish_date": "20.08.2019",
"status": "SAVED"
}]
I've attempted using the code below, but it doesn't give me the desired output. It only adds one matching id.
let i = 0;
firstInput.forEach( function( item ) {
var artikal = item.id;
secondInput.forEach( function( data ) {
if(artikal === data.id_artikla){
firstInput[i].status = "SAVED";
} else {
firstInput[i].status = "SAVE_ME";
}
});
i++;
});
Does anyone have a solution to achieve the desired output with pure vanilla JS? - Note: the list is over 100 indexes long. Speed is crucial.