Compare two json files and add number to object if object with same value is still there - javascript

Lets say i have 2 Json responses from a server, one of which is 30 seconds older that the new one. How would i be able to check if an object is still inside the response and after testing if it is still there update an object in another json file to add +1 to the number of that object.
(an example because i can´t explain)
JSON coming in
"names and id´s in json changed"
{
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [
{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
}
After cutting out wanted values it looks like this :
[
'07bda75d-d8d2-4108-94a7-ba2c09127nsj',
'8d8aac43-112b-402b-8771-67b49183lazf',
'67d8a66b-ce37-439f-9020-e6de827dn2o9'
]
What i want to do
Now upon a new response coming in i want to update another json file which should idealy look something like this...
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
...and add 1 to the number behind a the certain playerid.

Something like this should work.
let samplePayload = {
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
};
let previousResponseIds = [];
let trackingObj = {};
function responseMiddleware(payload) {
let responseIds = payload.players.sample.map(v => v.id);
let matches = previousResponseIds.filter(v => responseIds.find(x => x === v));
for (let i = 0; i < matches.length; i++) {
if (trackingObj.hasOwnProperty(matches[i])) trackingObj[matches[i]] += 1;
else trackingObj[matches[i]] = 0;
}
previousResponseIds = responseIds;
}
/*UI below*/
let pre = document.getElementsByTagName('pre')[0];
(function updateUI() {
pre.innerText = JSON.stringify(trackingObj, null, 1);
setTimeout(updateUI, 200);
})();
document.getElementById("AddResponse").addEventListener("click", function() {
responseMiddleware(samplePayload);
});
<strong>trackingObj:</strong>
<pre></pre>
<button id="AddResponse">Simulate Response</button>

Let's start with
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
let mainObj = JSON.parse(response1);
let players = JSON.parse(response2);
for (let entry of mainObj.players.sample) {
if (players.players.indexOf(entry.id) > -1) {
players.players[entry.id]++;
}
}
I don't have a chance to test it right this moment, give it a shot, and it should put you on the right track.

Related

Replace key and strings in array in JSON

I have this JSON below:
{
"class": "List",
"list": [{
"name": "HandsUp"
"schedule": {
"type": "probability",
"theme": "Regular",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}, {
"name": "Listing",
"waitingScreenInfo": {
"__class": "WaitingScreenInfo",
"getRecapTime": 1607687753.7949834
},
"schedule": {
"type": "Waiting2",
"theme": "Listing",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}
]
}
and I have this one:
{
"HandsUp": "HandsDown",
"Listing": "ImgList",
"Waiting2": "UpNDown"
}
The equivalent of the strings in the first JSON are in the second JSON and I wonder how can I make a function that finds the equivalents of the strings in the first JSON and then replace all of them even though if there is more than one?
You can do this
Go through the array
check if property name equals the key from your "repl" object
if yes reassign the value with the one in your "repl" object
let stru = {
"class": "List",
"list": [{
"name": "HandsUp",
"schedule": {
"type": "probability",
"theme": "Regular",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}, {
"name": "Listing",
"waitingScreenInfo": {
"__class": "WaitingScreenInfo",
"getRecapTime": 1607687753.7949834
},
"schedule": {
"type": "Waiting2",
"theme": "Listing",
"occurance": {
"next": 1607687249008.9834,
"prev": null
}
}
}]
}
const repl = {
"HandsUp": "HandsDown",
"Listing": "ImgList",
"Waiting2": "UpNDown"
}
console.log("Before ", stru)
stru.list.forEach(element => {
// keys and values correspond at the index
let keys = Object.keys(repl);
let values = Object.values(repl);
for (let i = 0; i < keys.length; i++) {
if (keys[i] === element.name) {
element.name = values[i];
}
}
});
console.log("Afterwards ", stru)

javascript remove duplicates from array of objects

I have below array of objects,
var parsedData = [
{
"ID": "16",
"DESCRIPTION": "SMAATO"
},
{
"ID": "26",
"DESCRIPTION": "BIDSWITCH"
},
{
"ID": "1572",
"DESCRIPTION": "BIDSWITCH"
}
]
i have removed duplicate from this using below code,
var flags = [], l = parsedData.length, i;
for( i=0; i<l; i++) {
if( flags[parsedData[i].DESCRIPTION]){
if(attribute.toLowerCase() == "supply"){
console.log("coming!!"+parsedData[i].ID+"---"+parsedData[i].DESCRIPTION);
}
continue;
}
flags[parsedData[i].DESCRIPTION] = true;
groups_array.push({
id: parsedData[i].ID,
text: parsedData[i].DESCRIPTION
});
}
but what i need to achive is, if id is differnt and description same means need to append id to first one and remove duplicate one like this,
[
{
"ID": "16",
"DESCRIPTION": "SMAATO"
},
{
"ID": "26,1572",
"DESCRIPTION": "BIDSWITCH"
}
]
How to get this one help me please...
Try:
if (flags[parsedData[i].DESCRIPTION]) {
let id = groups_array.map(item => item.text).indexOf(parsedData[i].DESCRIPTION);
groups_array[id].id = groups_array[id].id + "," + parsedData[i].ID
continue;
}

Find and replace in nested objects

I'm struggling with the following issue:
I have a nested object. From the server I get a response with an object with changed values. So I want to find the object in my nested object and replace it.
My object has a structure like this:
$scope.page = {
id: 5,
label: 'myPage',
items : [
{
"type": "Container",
"id": 1,
"label": "header",
"items": [
{
"type": "Container",
"id": 2,
"label": "left",
"items": [
{
"type": "Menu",
"label": "settings-menu",
"id": "5"
},
{
"type": "Menu",
"label": "main-menu",
"id": "7"
}
]
},
{
"type": "Container",
"id": 4,
"label": "right",
"items": [
{
"type": "Post",
"label": "contact",
"id": "25"
}
]
}
]
},
{
"type": "Postlist",
"label": "nieuwsberichten",
"id": "17"
},
{
"type": "HTML",
"label": "over deze site",
"id": "18"
},
{
"type": "Other",
"label": "twitter feed",
"id": "19"
}
]
}
From the server I get a new object:
var newItem = {
"type": "Post",
"label": "contact",
"id": "25"
}
How can I update the object inside $scope.page the right way? I've tried the following:
$scope.findAndReplace(newItem,$scope.page.items);
$scope.findAndReplace = function(newItem, items) {
for (var i = 0; i < items.length; i++) {
if (items[i].id == newItem.id) {
items[i] = newItem;
} else if (items[i].items) {
$scope.findAndReplace(newItem, items[i].items);
}
}
}
and:
var oldItem = $scope.findById(item.id, $scope.page.items);
oldItem = newItem;
$scope.findById = function(id, items) {
var match = null;
angular.forEach(items, function(i){
if (match == null) {
if (i.id == id) {
match = i;
} else if (i.items) {
match = $scope.findById(id, i.items)
}
}
})
return match;
}
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
Anyone an idea to handle this?
Your example looks fine, can't understand why they are not working.
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
You can keep object reference by using angular.copy(newItem, oldItem)
Hi I have created a fiddle for you.
click for fiddle
for(var indx=0; indx < $scope.page.items.length; indx++) {
var tmpObj = $scope.page.items[indx];
if(tmpObj.hasOwnProperty('items')) {
// check inside
for(var indx1=0; indx1<tmpObj.items.length; indx1++ ) {
var innerObj = tmpObj.items[indx1];
// check for next level
if(innerObj.hasOwnProperty('items')) {
for(var counter=0; counter< innerObj.items.length; counter++) {
var thirdTmp = innerObj.items[counter];
console.log('3rd level inner object', thirdTmp);
if(thirdTmp.id === newItem.id) {
innerObj.items[counter] = newItem;
tmpObj.items[indx1] = innerObj;
$scope.page.items[indx] = tmpObj;
}
}
}
}
} else if(tmpObj.id === newItem.id) {
$scope.page.items[indx] = newItem;
}
};

Use array of strings to create a multi level object, parsing arrays into JS objects

I have this array that needs to be parsed into a useful object. The names of each value are a collection of namespaces separated by / characters. The values between each '/' need to be turned into a JS Objects property:
"status": [
{
"message": "OK",
"name": "/Computer",
"values": []
},
{
"name": "/Computer/CPU Usage",
"values": []
},
{
"name": "/Computer/CPU Temp",
"values": []
},
{
"name": "/Computer/hardware/memory",
"values": []
}
]
I need it to become this:
"status": {
"computer": {
"CPU Usage": {
"values": []
},
"CPU Temp": {
"values": []
},
"hardware": {
"memory": {
"values": []
}
}
}
}
So far I have done this:
var statii = status, // from above..
_parsedStatii = {};
for (var i = 0; statii.length < 0; i ++) {
var _nameSpaces = statii[i].name.split('/');
// Start at 1 because index 0 is empty (before the first slash)
if (!_parsedStatii[_nameSpaces[1]]) {
_parsedStatii[_nameSpaces[1]] = {};
}
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]] = {};
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]] = {};
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]] = {};
}
Obviously it is no where near right, I have tried a lot of recursive functions but am at a bit of a loss. This example gives the clearest representation of what I am trying to achieve. Any ideas? (Please excuse code typos, it was paraphrased)
You could split the name and build an object upon.
var data = { "status": [{ "message": "OK", "name": "/Computer", "values": [] }, { "name": "/Computer/CPU Usage", "values": [] }, { "name": "/Computer/CPU Temp", "values": [] }, { "name": "/Computer/hardware/memory", "values": [] }] },
object = {};
data.status.forEach(function (a) {
a.name.slice(1).split('/').reduce(function (o, k) {
return o[k] = o[k] || {};
}, object).values = a.values;
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Making objects into array

I would like to make a JSON object as follows:
{
"PROMO": {
"ID": 1,
"NAME": "PROMO ONE",
"BUNDLES": {
"0": {
"BUNDLE": {
"BUNDLE_ID": 1,
"BUNDLE_NAME": "BUNDLE ONE"
},
"ARTICLE": {
"ARTICLE_IDS": "550,398,475"
}
},
"1": {
"BUNDLE": {
"BUNDLE_ID": 1,
"BUNDLE_NAME": "BUNDLE ONE"
},
"ARTICLE": {
"ARTICLE_IDS": "125,250,323"
}
}
}
}
}
What I want to do, combine BUNDLE and ARTICLE object then push into BUNDLES array. I tried many way but no success to combine two object.
For instance, I tried following:
var BUNDLES = [];
var BUNDLE = {};
var ARTICLE = {};
BUNDLE.BUNDLE_ID = 1;
BUNDLE.BUNDLE_NAME = "BUNDLE ONE";
ARTICLE.ARTICLE_IDS = "550,398,475";
// here, I want to combine ARTICLE and BUNDLE then push into array
BUNDLES.push(BUNDLE)
This will do ya. Probably there's a neater way but this does what you want I hope.
http://jsfiddle.net/558BN/
var json = {
"PROMO": {
"ID": 1,
"NAME": "PROMO ONE",
"BUNDLES": {
"0": {
"BUNDLE": {
"BUNDLE_ID": 1,
"BUNDLE_NAME": "BUNDLE ONE"
},
"ARTICLE": {
"ARTICLE_IDS": "550,398,475"
}
},
"1": {
"BUNDLE": {
"BUNDLE_ID": 1,
"BUNDLE_NAME": "BUNDLE ONE"
},
"ARTICLE": {
"ARTICLE_IDS": "125,250,323"
}
}
}
}
}
var array = [];
for(var i in json.PROMO.BUNDLES){
var obj = {};
for(var j in json.PROMO.BUNDLES[i]){
obj[j] = json.PROMO.BUNDLES[i][j]
//console.log(j + " " + obj[j]);
}
array.push(obj);
}
json.PROMO.BUNDLES = array;
console.log(json.PROMO.BUNDLES);

Categories