javascript remove duplicates from array of objects - javascript

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;
}

Related

IE9: Manipulate a string if the value of the string has a match in an array of Objects

In the below function setChildNumber Strings like 'Child2' or 'Child3', 'Child4' are passed.
'family' variable contains array of object. I've added a sample data. This code needs to support IE9. So I can't use 'find'.
Objective:
I need help finding the index from family array of objects, if
family.type === child and id === memberID, the replace memberID with
index from family[]
function setChildNumber(member) {
var family = JSON.parse(sessionStorage.getItem('memberObject'));
var memberID = +member.match(/\d+/)[0];
if(!family) return;
var index = member.toLowerCase().indexOf('child') === 0
&& family.find(function(elem) {
return (elem.id === memberID);
}).index;
return member.slice(0, member.length-1) + ' ' + index;
}
family = [
{
"id": 1,
"type": "SELF",
"birthday": "10/10/1980",
"age": 40
},
{
"id": 2,
"type": "CHILD",
"index": 1,
"birthday": "10/10/2001"
},
{
"id": 3,
"type": "SPOUSE",
"birthday": "10101980",
"age": 40
},
{
"id": 4,
"type": "CHILD",
"index": 2,
"birthday": "10102010",
"age": 10
}
]
You can use a simple for loop.
var idx = -1;
for(var i = 0; i < family.length; i++){
if(family[i].type.toLowerCase() === 'child' && family[i].id === memberID){
idx = i;
break;
}
}

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

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.

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;
}
};

How to check that object with same ID (or any other attribute ) exists in array of objects?

I have following array:
var array = [
{
"milestoneTemplate": {
"id": "1",
"name": "TEST1"
},
"id": "1",
"date": "1416680824",
"type": "ETA",
"note": "Note",
"color": "66FF33"
},
{
"milestoneTemplate": {
"id": "2",
"name": "Test 2"
},
"id": "2",
"date": "1416680824",
"type": "ATA",
"note": "Note 22",
"color": "66FF00"
}
];
And now i would like to check in forEach loop that object (which is passed in param of the function) is existing in array by his ID.
In case that not = do push into existing array.
arrayOfResults.forEach(function(entry) {
if(entry != existingInArrayByHisId) {
array.push(entry);
}
});
Thanks for any advice
You could create a helper function thats checks if an array contains an item with a matching property value, something like this:
function checkForMatch(array, propertyToMatch, valueToMatch){
for(var i = 0; i < array.length; i++){
if(array[i][propertyToMatch] == valueToMatch)
return true;
}
return false;
}
which you can then use like so:
arrayOfResults.forEach(function (entry) {
if (!checkForMatch(array, "id", entry.id)) {
array.push(entry);
}
});

Creating and Updating JSON

I can create a Json object as here
How to create json by javascript for loop?
great!
and I have created one like below
[
{
"id": "10",
"userName": "kuttan"
},
{
"id": "11",
"userName": "kunjan"
}
]
Suppose I want to update name of the user with id 10 to "new name"
what should i do?(i dont know the index is 1)
Loop over your array of objects (because that's what it is), and check the "id" attribute of each object.
var list = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];
for (var i=0;i<list.length;i++) {
if (list[i].id == "10") {
alert(i);
};
};
You could then abstract this into some nice function.
function findIndexById(list, id) {
for (var i=0;i<list.length;i++) {
if (list[i].id == id) {
return i;
};
};
return -1;
};
Then use it as follows:
var list = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];
var index = findIndexById(list, "10");
if (index !== -1) {
list[index].userName = "new username";
};
You can loop through the array and check the id property of the object in the current iteration. If it's 10, assign the new username to userName.
var json = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ],
len = json.length,
obj;
while(len--) {
obj = json[len];
if (obj.id == 10) {
obj.userName = 'foobar';
}
}
console.log(json); // outputs [{id:"10", userName:"foobar"}, {id:"11", userName:"kunjan"}]

Categories