Delete an object in Scope - javascript

This question might not even be related to angularjs and the solution could be plain old js or jquery. But that is what i what to find out.
I want to implement a delete functionality for a particular user and i am wondering if there is a easier way to do this in angularjs or should it be plain old JS?
i have a fairly complex object for eg (going up to 4 levels):
{
"Department": [
{
"Name": "Accounting",
"users": [
{
"id": "1",
"firstName": "John",
"lastName": "Doe",
"age": 23
},
{
"id": "2",
"firstName": "Mary",
"lastName": "Smith",
"age": 32
}
]
},
{
"Name": "Sales",
"users": [
{
"id": "3",
"firstName": "Sally",
"lastName": "Green",
"age": 27
},
{
"id": "4",
"firstName": "Jim",
"lastName": "Galley",
"age": 41
}
]
}
]
}
this is displayed in a ng-repeat where we should Department and username. If I want to delete a particular user i make an api call and on success of it, I want to delete that object. so i have a js method like this
function DeleteUser(user) {
$.each(ctrl.UserData, function(index, value) {
var filteredPeople = value.filter((item) => item.id !== user.id);
});
The question I have is, if i want to delete this object is there any easier way to delete from model since i have the object here or i have to do the classic jquery way of using like $.grep or filter to iterate through each object and match by id and then delete it?

Presumably, you're iterating over the departments (accounting, sales) in your template, and then over the users in that department.
So you could have, in your template:
<button ng-click="deleteUser(user, department)">...</button>
And the method could thus be as simple as
$scope.deleteUser = function(user, department) {
// delete user from backend, then
department.users.splice(departments.users.indexOf(user), 1);
}
If you really don't want to pass the department, then loop over the departments, and use the above if departments.users.indexOf(user) returns a value that is >= 0.

Related

Does reading file in node.js guarantee the order of items

In my node.js application I have test data file that I read to populate some inputs. The test file contains an array of objects.
I use for reading:
data = fs.readFileSync(fileName, "utf8");
My test file:
[
{
"firstname": "John",
"lastname": "Doe",
"birthdate": "01/01/1970"
},
{
"firstname": "El",
"lastname": "Maestro",
"birthdate": "01/01/1989",
"isDeleted": true
}
]
So the question is - when I read this file is it guaranteed that I will always get object with name "John" at index 0, and "El" at index 1?
Arrays always ensures order in JS
BUT
Keys inside objects doesnot ensure order in JS, they are 'unordered key value pair'
To answer your question:
when I read this file is it guaranteed that I will always get object with name "John" at index 0, and "El" at index 1
yes
BUT
The keys in the resulting object can be unordered, eg: it can be
{
"firstname": "John",
"lastname": "Doe",
"birthdate": "01/01/1970"
}
or
{
"lastname": "Doe",
"birthdate": "01/01/1970",
"firstname": "John"
}
etc...

How to iterate through following compex JSON data and access its all values including nested?

I have following JSON data but I don't know how to iterate through it and read its all values:
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
I would like to use following methods to do the needful:
Using for in loop
Using simple for loop
Using $.each in jQuery
I will prefer to display above values in <ul> <li> nicely formatted.
Also, please suggest me what will be look of above JSON data if I put it in an external .json file?
You can use for in loop to iterate over the object, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.
Now about accessing the object, let's say I have a JSON like
var myJson={name:"john",age:22,email:"email#domain.com"};
and I need to access the value of name i would simply use . operator using the myJson variable i.e console.log(myJson.name) will output john. because it will be treated as an object, now if I make a little change and make the object like below
var myJson=[{name:"john",age:22,email:"email#domain.com"}];
now if you try to access the value of the property name with the same statement above you will get undefined because the [] will now treat it as an object(JSON) with an array of 1 person or a JSON Array, now if you access it like console.log(myJson[0].name) it will print john in console what if there was more than one person in the array? then it will look like following
var myJson=[
{name:"john",age:22,email:"john#domain.com"},
{name:"nash",age:25,email:"nash#domain.com"}
];
console.log(myJson[0].name) will print john and console.log(myJson[1].name) will print nash so as I mentioned in the start that you should use for in loop for iterating over an object and if we want to print all the names of the person in the JSON Array it will be like.
for(var person in myJson){
console.log(myJson[person].name, myJson[person].age, myJson[person].email);
}
it will output in the console like below
john, 22, john#domain.com
nash, 25, nash#domain.com
I have tried to keep it simple so that you understand you can look into for in and hasOwnProperty, in your case you have a nested object in which property/key subject is an array so if I want to access the first_name of student1 i will write students.student1.first_name and if I want to print the name of the first subject of student1 I will write students.student1.subject[0].name
Below is a sample script to print all the students along with their subjects and marks and personal information since you JSON is nested I am using a nested for in, although Nested iterations are not necessarily a bad thing, even many well-known algorithms rely on them. But you have to be extremely cautious what you execute in the in the nested loops.
For the sake of understanding and keeping the given example of json object, i am using the same to make a snippet. Hope it helps you out
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
$("#print").on('click', function() {
for (var student in students) {
console.log(students[student].first_name + '-' + students[student].last_name);
for (var subject in students[student].subject) {
console.log(students[student].subject[subject].name, students[student].subject[subject].marks);
}
}
setTimeout('console.clear()', 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="print" value="print-now">

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

How to do ng-repeat on $firebaseArray output with multiple levels?

I am using $firebaseArray for collecting the data from Firebase. Output is as follows:
[
{
"BankAccount": {
"AccountHolder": "Tom Antony",
"AccountNumber": "56767887"
},
"Info": {
"BillingAddress": {
"City": "XYZ",
"State": "ABC"
},
"FullName": "Tom Antony",
"PhoneNumber": "634762347"
},
"$id": "dGUZX5SWi7aP0SNYLYqEiMdCYAS2",
"$priority": null
},
{
"Campaigns": {
"Settings": {
"Active": true
}
}
},
"Info": {
"BillingAddress": {
"City": "ABC",
"State": "DFG"
},
"FullName": "Mario",
"PhoneNumber": "634762347"
},
"$id": "tBqGZ7g6VwNYOWoVy7C1FHKZKFS2",
"$priority": null
}
]
My js is as follows:
const rootRef = firebase.database().ref().child('Users');
$scope.users = $firebaseArray(rootRef);
Each Array element will have different type of objects, but each will have a similar object called Info, which contains a field for FullName I need to apply ng-repeat on this FullName. My implementation is as shown below:
<div ng-repeat="user in users.Info">
<p ng-bind="user.FullName"></p>
</div>
But its not working. What are the mistakes I made here?
You are trying to iterate on the wrong property. You have two objects (user) which each have an Info property that you want the FullName from. You do not have two Info objects. Therefore, you should be iterating over the users, not iterating over users.Info.
Try this instead:
<div ng-repeat="user in users">
<p ng-bind="user.Info.FullName"></p>
</div>
Also, your object you pasted here wasn't valid JSON, you had an extra }.
Full Working example: http://plnkr.co/edit/ryfjhO0c3egHfKnaL9SQ?p=preview

Reading JSON data for a particular ID

I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place

Categories