Hi I have an object which has only one property as "contacts" and its value is an array which contains 4 objects and each object has properties like email, firstname etc...
I want to remove a particular object from that array by matching its email property with an given email.
I am trying to iterate through that array using $.each loop in jQuery and trying to match email in each iteration and when matched I am trying to delete that object using splice but it is not working.
Below is a sample code similar to what I am implementing:
//main object with all the data
var data = {
"contacts": [
{
"email": "jonas.sultani#hellyhansen.com",
"firstname": "Jonas",
"lastname": "Sultani",
"prefix": "Mr",
"title": "Consultant",
"company": "Helly Hansen",
"phone": "+49 6245 99334",
"fax": "+49 6245 99335"
},
{
"email": "james.simmons#boeing.com",
"firstname": "James H",
"lastname": "Simmons",
"prefix": "Mr",
"title": "AP Lead",
"company": "Boeing",
"phone": "+1 112-445-6684",
"fax": ""
},
{
"email": "slmarino#boehringer-ingelheim.com",
"firstname": "Stephanie",
"lastname": "Marino",
"prefix": "Mrs",
"title": "Project Manager",
"company": "Boehringer Ingelheim",
"phone": "+1 650-554-5124",
"fax": ""
}
]
}
//extracting array from the data object
var myArray = data.contacts;
//sample email to match and delete the object
var email = "jonas.sultani#hellyhansen.com";
//function to delete the object containing the passed email
function deleteElement(myId){
//iterating the myArray to check the email with the given email
$.each(myArray, function(key, val){
var email = val.email;
//if the email is matched the particular object on the current index in the array is deleted using splice
if(myId === email){
myArray.splice(key,1);
return;
}
});
}
//calling the function and passing the email to delete the object
deleteElement(email);
//printing the modified array
console.log(myArray);
This method is not working so can you please let me know how can I make this work.
Note: I don't want to modify anything with the data object or myArray but I want to find solution with the current situation
Big Thanks
I would advise against the use of jQuery (because you don't need it) and against any for/while loop, and just KISS it :
function deleteElementWithEmail(data, email) {
return data.filter(function (current) {
return current.email !== email
})
}
With all your code:
//main object with all the data
var data = {
"contacts": [
{
"email": "jonas.sultani#hellyhansen.com",
"firstname": "Jonas",
"lastname": "Sultani",
"prefix": "Mr",
"title": "Consultant",
"company": "Helly Hansen",
"phone": "+49 6245 99334",
"fax": "+49 6245 99335"
},
{
"email": "james.simmons#boeing.com",
"firstname": "James H",
"lastname": "Simmons",
"prefix": "Mr",
"title": "AP Lead",
"company": "Boeing",
"phone": "+1 112-445-6684",
"fax": ""
},
{
"email": "slmarino#boehringer-ingelheim.com",
"firstname": "Stephanie",
"lastname": "Marino",
"prefix": "Mrs",
"title": "Project Manager",
"company": "Boehringer Ingelheim",
"phone": "+1 650-554-5124",
"fax": ""
}
]
}
//extracting array from the data object
var myArray = data.contacts;
//sample email to match and delete the object
var email = "jonas.sultani#hellyhansen.com";
//function to delete the object containing the passed email
function deleteElementWithEmail(data, email) {
return data.filter(function (current) {
return current.email !== email
})
}
//calling the function and passing the email to delete the object
myArray = deleteElementWithEmail(myArray, email);
//printing the modified array
console.log(myArray);
Use a do..while loop or while loop to remove elements from an array within a loop
let i = 0;
let len = data.contacts.length;
do {
var email = data.contact[i].email;
if (myId === email) {
data.contacts.splice(i, 1);
break;
}
++i;
} while (i < len);
You can use array.filter function to get desired result.
//main object with all the data
var data = {
"contacts": [{
"email": "jonas.sultani#hellyhansen.com",
"firstname": "Jonas",
"lastname": "Sultani",
"prefix": "Mr",
"title": "Consultant",
"company": "Helly Hansen",
"phone": "+49 6245 99334",
"fax": "+49 6245 99335"
},
{
"email": "james.simmons#boeing.com",
"firstname": "James H",
"lastname": "Simmons",
"prefix": "Mr",
"title": "AP Lead",
"company": "Boeing",
"phone": "+1 112-445-6684",
"fax": ""
},
{
"email": "slmarino#boehringer-ingelheim.com",
"firstname": "Stephanie",
"lastname": "Marino",
"prefix": "Mrs",
"title": "Project Manager",
"company": "Boehringer Ingelheim",
"phone": "+1 650-554-5124",
"fax": ""
}
]
}
//extracting array from the data object
var myArray = data.contacts;
//console.log(myArray);
//sample email to match and delete the object
var email = "jonas.sultani#hellyhansen.com";
//function to delete the object containing the passed email
function deleteElement(myId) {
myArray = myArray.filter(function(el) {
return el.email != myId;
});
}
//calling the function and passing the email to delete the object
deleteElement(email);
//printing the modified array
console.log(myArray);
Related
I'm trying to omit req.body data, when updating a resource in a collection, with only the fields that are null or '' for that existing resource in the collection.
But this could also be generic, that's why the title is more generic.
Anyways, imagine the following:
We have a user in our database with the following data:
{
"firstName": "John",
"lastName": "Doe",
"address": {
"Address1": "Random street 1",
"City": "",
"Country": null
},
"email": ""
}
The user is trying to update the existing resource with the following data:
{
"firstName": "Mark",
"address": {
"Address1": "Random street 2",
"City": "NY",
"Country": "USA"
},
"email": "john.doe#mail.com"
}
Updated object should like like this:
{
"firstName": "John", // Unchanged because propety value already exists
"lastName": "Doe",
"address": {
"Address1": "Random street 1", // Unchanged because propety value already exists
"City": "NY", // Updated because existing value is empty ("")
"Country": "USA" // Updated because existing value is null
},
"email": "john.doe#mail.com" // Updated because existing value is empty ("")
}
I'm using mongoose, but I would rather implement this on the basic javascript object level
I am not aware of any library but below is the working example using recursion.
var oldObj = {
"firstName": "John",
"lastName": "Doe",
"address": {
"Address1": "Random street 1",
"City": "",
"Country": null
},
"email": ""
}
var newObj = {
"firstName": "Mark",
"address": {
"Address1": "Random street 2",
"City": "NY",
"Country": "USA"
},
"email": "john.doe#mail.com"
}
updateObject(oldObj, newObj);
function updateObject(oldObj, newObj) {
Object.keys(oldObj).forEach( key => {
if (oldObj[key] && typeof oldObj[key] === 'object') {
updateObject(oldObj[key], newObj[key]);
} else {
oldObj[key] = oldObj[key] || newObj[key];
}
});
}
console.log("Modified Obj: ", oldObj);
Hope this may help you.
So I have the following JSON. The result that I'm looking for is if there are multiple objects with the same site_id, to create an object which contains the site_id, an array of users, and the rest of the properties merged together.
I tried using reduce, but it's not working :D
Thank you in advance
{
"response": [
{
"site_id": "4587c4183c312dd82309be6cdae7bbd6",
"name": "esse",
"lat": 82.3172,
"lon": -30.0668,
"company": "256090f4d3a41f34096876b71ee03694",
"user_id": "2d3393051386426adca86c13362e6f46",
"UserName": "Juliet44",
"Password": "Test",
"FirstName": "Kristy",
"LastName": "Goldner",
"Company": "256090f4d3a41f34096876b71ee03694",
"Email": "Kassandra37#hotmail.com",
},
{
"site_id": "4587c4183c312dd82309be6cdae7bbd6",
"lat": 82.3172,
"lon": -30.0668,
"company": "256090f4d3a41f34096876b71ee03694",
"user_id": "2f2a174f63f7e277630eb808974dfd05",
"UserName": "Marguerite_Smith34",
"Password": "Test",
"FirstName": "Christian",
"LastName": "Gerhold",
"Company": "256090f4d3a41f34096876b71ee03694",
"Email": "Urban.Boyer#yahoo.com",
},
{
"site_id": "94fc61eee3c0d01abace7a2feb84bc4c",
"name": "blanditiis",
"lat": 13.3673,
"lon": 54.3085,
"company": "256090f4d3a41f34096876b71ee03694",
"user_id": "3f85f1a435df6c3ca4ac944116515c04",
"UserName": "Tyrell.Schimmel",
"Password": "Test",
"FirstName": "Lucius",
"LastName": "O'Conner",
"Company": "256090f4d3a41f34096876b71ee03694",
"Email": "Eino.Hackett#gmail.com",
},
]
}
Probably the rest operator is your friend. And im not shure if you really need to reduce, a simple forEach does it:
var hash={}, result = [];
response.forEach(function({site_id,...rest}){
if(!hash[site_id]){
result.push(hash[site_id]={site_id});
}
let el = hash[site_id];
for(key in rest){
if(el[key]){
el[key].push(rest[key]);
}else{
el[key] = [rest[key]];
}
}
});
function main(message){
...
phone= JSON.parse(message.phoneNumbers);
... }
My input JSON is
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
The result I receive is omitting the "phoneNumbers" but I do want it.
Your data is correct, when i JSON.parse it, i get everything allright.
But you don't seem to access to your data in the right way. You must first parse the whole JSON, then you have a javascript object, and only then you can acces your property.
in detail:
var obj = JSON.parse(message);
var phone = obj.phoneNumbers;
or in short:
var phone = (JSON.parse(message)).phoneNumbers;
I have JSON array with subarrays and I want to loop it and find if username of user is for example 'admin'. If so then create JSON array contains data belonging to user 'admin' (region, sport, city etc). I don't have idea how to find it in loop and then slice it. I'm sorry for stupid question but I'm a little lost.
This is JSON array with structure what I have:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
]
Edit:
the expected result of user 'admin' is then:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
}]
Loop through the array and pull out each item with a user with a username of admin:
var result = [];
var nameToSearchFor = 'admin';
for(var index = 0; index < arr.length; index++)
{
var item = arr[index];
if(item.user.username === nameToSearchFor)
{
result.push(item);
}
}
One solution to your problem is to search for the index that resides the admin username. In your case is at the 0 index of the json array provided. So you can get the entire object by the index, like this:
var i = 0;
for(; i< json.length; i++){
if(json[i].user.username === "admin") break;
}
With that now you can get the object with the admin data. Like this:
json[i].user.firstName
Check this plunk here
EDIT
If you want just to get that slice to a new array perhaps then you can just slice that piece of the json array, now that you have the index.
var newArray = json.slice(i, i+1);
You can use an open source project like jinqJs to perform SQL like queries on arrays.
var data = [
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
];
var result = jinqJs()
.from(data)
.where(function(row){return row.user.username==='admin';})
.select();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>
I have an array of object having multiple attributes. I have a requirement to filter the array based on many attributes. lets say all the objects having firstname as "John" and who lives in "India" and "30" years of age.
I have done this by putting && condition after each filtering, but I am planning to use Underscore.js in my project. Please let me know if Underscore.js can help me write in a more elegant manner?
Json Data:
{
"recordsTotal": 5,
"recordsFiltered": 5,
"aaData": [
{
"firstname": "John",
"lastname": "Kumar",
"city": "Dhaka",
"country": "Bangladesh",
"age": "30"
},
{
"firstname": "John",
"lastname": "Wells",
"city": "Katmandu",
"country": "Nepal",
"age": "28"
},
{
"firstname": "Praveen",
"lastname": "Garg",
"city": "columbo",
"country": "Srilanka",
"age": "40"
},
{
"firstname": "Joe",
"lastname": "Wells",
"city": "Luton",
"country": "UK",
"age": "12"
},
{
"firstname": "Rita",
"lastname": "Wahlin",
"city": "houston",
"country": "USA",
"age": "28"
}
]
}
There is a function _.filter which lets you pass every element of a collection to a function to test whether to include it in the returned filtered list.
So I think you would need something like:
var filtered = _filter(data.aaData, function(item) {
return (item.firstname == 'John') && (item.country == 'India') && (age == '30');
})
See: http://underscorejs.org/#filter
Take a look at the filter method of underscore, you can pass it in a list of objects, and arbitrarily specify the constraints for each field of the object:
var filtered = _.filter(data, function(item){
return item.firstname == "John" && item.country == "India" && item.age == 30;
});
alternatively if you have a user defineable list of filters you could:
var filters = {
"firstname":"John",
"country":"India",
"age":"30"
}
var filtered = _.filter(data, function(item){
for(filter in filters){
if(item[filter] != filters[filter]){ return false;}
}
return true;
});
Try this,
It is fast regular expression, no need to include extra js file except jQuery.
var result = $.grep(xx.aaData, function (e) { return e.firstname == 'john' && e.country == 'india' && e.age == '30'; });
where xx is your main json object