Remove item from json object on checkbox uncheck in angularjs - javascript

I am using angularjs v1.4.7. I have fetched result set from db and constructed data as jsonobject.
$scope.originalEmpList=
{
"depts": [
{
"id": 1,
"name": "IT",
"software_team": "Ram, Rahim",
"hr_team": "",
"fin_team": ""
},
{
"id": 2,
"name": HR,
"software_team": "",
"hr_team": "Mohan",
"fin_team": ""
},
{
"id": 3,
"name": PM,
"software_team": "Ram",
"hr_team": "Mohan",
"fin_team": "John"
}
],
"softwarelist": [
{
"id": 1,
"employee_name": "Ram",
"employee_role": "Software",
"dept_id": "1"
},
{
"id": 2,
"employee_name": "Rahim",
"engineer_role": "Software",
"dept_id": "1"
},
{
"id": 3,
"employee_name": "Ram",
"engineer_role": "Software",
"dept_id": "3"
}
],
"hrlist": [
{
"id": 4,
"employee_name": "Mohan",
"employee_role": "HR",
"dept_id": "2"
},
{
"id": 5,
"employee_name": "Mohan",
"employee_role": "HR",
"dept_id": "3"
}
],
"finlist": [
{
"id": 6,
"employee_name": "John",
"employee_role": "Account",
"dept_id": "3"
}
]
}
and showing below table on UI side from above jsonobject
Select All Checkbox Dept Softwares HRs Fins
Checkbox1 IT Ram, Rahim
Checkbox2 HR Mohan
Checkbox3 PM Ram Mohan John
Based on above checbox selection respective team members will be shown.
For Eg: If Checkbox1 is selected then only show names for that dept.
Softwares : Ram, Rahim
Similarly if we select checkbox1 and checkbox2 then show names for checked depts.
Softwares : Ram, Rahim
Hrs: Mohan
And if we select all 3 checkboxes then show names.
Softwares : Ram, Rahim, Ram
Hrs: Mohan, Mohan
Fins: John
I have kept unchanged the original emp list and copied it to employeeList
$scope.employeeList = $scope.originalEmpList;
Update object based on checkbox selection.
$scope.UpdateOnCheckUncheck = function () {
$scope.employeeList = $scope.originalEmpList;
$scope.filteredArtist = [];
// Collect unchecked depts
$scope.unchecked_depts = filterFilter($scope.employeeList.depts,
function (dept) {
return !dept.Selected;
});
$scope.filteredSoftware= [];
// Passing unchecked depts to remove from employeelist
angular.forEach($scope.unchecked_depts, function(dept) {
$scope.updateCheckedDept(dept);
});
};
$scope.updateCheckedDept = function(dept) {
**// Approach 1 using reduce to copy into new array and then assign back to employeeList**
Object.keys($scope.employeeList.softwarelist).reduce((object,
key) => {
if (dept.id !=$scope.employeeList.softwarelist[key].dept_id)
{
$scope.filteredArtist.push($scope.prismlist.artistlist[key]);
}
//return object
}, {})
$scope.employeeList.softwarelist= $scope.filteredSoftware;
**//Approach 2 using splice
angular.forEach($scope.employeeList.softwarelist,
function(soft, index){
if(dept.id === soft.dept_id){
$scope.employeeList.softwarelist.splice(index);
}
});
**//Approach 3 using slice**
};
//Approach 4 - Thinking to call DB and construct query and filter at server side but calling db on every checkbox change will be costly.
Actually after updating back to $scope.employeeList , it works fine for the first time uncheck but when uncheck another checkbox i assign $scope.employeeList = $scope.originalEmpList; but this doesn't get the initial data fetched from db rather than it updated to first time uncheck object value.
On Every check/uncheck how to update employeelist to populate the output as shown above. Also suggest me the best approach to use in terms of performance. Thanks in advance

$scope.employeeList = $scope.originalEmpList;
is like referencing to $scope.originalEmpList. Any updates to $scope.employeeList is the same as updating $scope.originalEmpList.
Instead, you try angular.copy() which creates a deep copy of the array.
$scope.employeeList = angular.copy($scope.originalEmpList);

Related

How to get the filtered object into the json-server when an end user does a rough search?

I am using json-server as my fake API data. I am implementing the search functionality to it. I created an endpoint like this -
getData : ( searchTerm : string ) => axios.get(`http://localhost:3000/books?=${searchTerm}`).then((response) => setData(response));
and I am utilizing into my input field to get the searched results.
Let's say My json object coming back from the Json-server is as follows -
[
{
"Id": 1,
"name" : "car"
},
{
"Id": 2,
"name" : "bike"
},
{
"Id": 3,
"name" : "ninja bike"
}]
now, the problem is , when I search for "car", it gives me the json result.
but, when I search for "brand new car", it should give me the "car's" object at least, as word "car" is a match. but it is giving me [], empty array.
So please suggest me how could i look for specific words into my json-server's data?
so that whenever , the end user even make a vague unstructured search, it should look for specific words like "car", in this case and return that car object.
You can make a simple filter to check if your string is in there
let json = [{
"Id": 1,
"name": "car"
},
{
"Id": 2,
"name": "bike"
},
{
"Id": 3,
"name": "ninja bike"
}
]
let searchString = "brand new car".split(" ") // ["brand", "new", "car"]
let filter = json.filter(json => searchString.includes(json.name))
if (filter.length) {
console.log(filter[0].name)
console.log(filter[0].Id)
}
else console.log("not found")

How do I verify and count the presence of specific data in an associative array?

I have a question about manipulating data in an associative array.
What I want to do
I want to verify if an order exists in sellingItems.
Background(why?)
I want to check if there is an order to return the number of products in stock as a response.
Question
I want to check if a specific data (order) exists in an associative array and calculate the inventory count.
public calculateStockQuantity(itemInstances) {
const stockQuantity = //We want to count the number of items in stock. In this case, we want it to be 2 (calculated based on whether the data exists in sellingItem.order or not).)
  return stockQuantity;
}
Associative array of targets
//There are three itemInstances for one product because the number of products sold is three.
itemInstances =
[
{
"id": "1",
"sellingItem": [
{
"id": 1,
"price": 3000,
"orderedItem": [
{
"id": 1
              "ordered_at": "2021-04-01 10:00:00"
}
]
}
]
},
{
"id": "2",
"sellingItem": [
{
"id": 2,
"price": 3000,
"orderedItem": []
}
]
},
{
"id": "2",
"sellingItem": [
{
"id": 2,
"price": 3000,
"orderedItem": []
}
]
}
]
Sorry for asking like a newbie.
Please check if this is something you are looking for, assuming if orderedItem array is empty then that sellingItem will be counted as in stock
let count = itemInstances.filter(({sellingItem : [{ orderedItem }]}) => orderedItem.length === 0).length;
console.log(count); //return 2 based on question data

unable to push and append data to the state using React js

here i state with data
state = {
Response: [
{
"id": "15071",
"name": "John",
"salary": "53",
"age": "23",
"department": "admin"
},
{
"id": "15072",
"name": "maxr",
"salary": "53",
"age": "23",
"department": "admin"
},
{
"id": "15073",
"name": "Josef",
"salary": "53",
"age": "23",
"department": "admin"
},
{
"id": "15074",
"name": "Ye",
"salary": "53",
"age": "23",
"department": "admin"
}
]
i am displaying these records in the table. In table u will see 10 records and there will be a button on top of table so if append button is pressed then 10 records has to be added on every button press and the data has to be same but it has to be appended using the below logic i am trying to set the state by pushing 10 records and trying to append it for ex if i have 1,2,3,4,5,6,7,8,9,10 if i press append 1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10 has to be apeended
appendEmployees() {
var reLoadCount = 1;
for (let i = 0; i < 10; i++) {
const myObj = {
id: 0,
name: '',
salary: 0,
department: ''
};
myObj.id = +this.setState.employee[i].id + (reLoadCount * 10);
myObj.name = this.setState.employee[i].name;
myObj.salary = this.setState.employee[i].salary;
myObj.department = this.setState.employee[i].department;
this.setState.employee.push(myObj);
}
reLoadCount++;
}
am i doing some thing wrong here
If I get this right you're trying to add 10 duplicates of the objects in the this.state.employee array, the only difference between these new objects and the existing ones is their id.
If that is the case, here is how you can do that:
appendEmployees() {
this.setState(prevState => {
// Get the biggest ID number.
const maxId = Math.max(...prevState.employee.map(e => parseInt(e.id)));
// create 10 new employees copies of the first 10.
const newEmployees = prevState.employee.slice(0, 10).map((e, i) => ({
...e,
id: (maxId + i + 1)
}));
// return/update the state with a new array for "employee" that is a concatenation of the old array and the array of the 10 new ones.
return {
employee: [...prevState.employee, ...newEmployees]
}
});
}
I've added some comments to the example to explain what it does.
The important thing is this.setState which is the function used to update the state, here, I've used it with a function as the first parameter (it works with objects as well), I've did that because it is the preferred way of generating a new state that is derived from the old state.

change row background color Jquery

I have called a webapi and I got json data
{
"orderId": 26,
"userId": "53cf1e15",
"user": {
"editablePropertyNames": [],
"email": "rajesh#tech.com",
"firstName": "Rajesh",
"id": "53cf1e15",
"identities": [],
"lastName": "kumar",
"missingProperties": [],
"phoneNumber": "45877298"
},
"locationId": 4024,
"pickupType": 1,
"pickupTimeUtc": "2015-11-27T17:33:00.417"
},
{
"orderId": 601,
"userId": "06bf5983",
"user": {
"editablePropertyNames": [],
"email": "rtest#wa.com",
"firstName": "Rakesh",
"id": "06bf5983",
"identities": [],
"lastName": "Pkumar",
"missingProperties": [],
},
"locationId": 424,
"pickupType": 1,
"pickupTimeUtc": "2016-11-16T21:30:00",
"total": 4.32,
"tax": 0.83
}
var PickupMethodEnum = _enum({
DineIn: 1, DriveThru: 2, TakeOut: 3
})
index.html
I have 5 columns
#imageIndicator Name PickupName Total scheduledTime
car.png Kumar 1 4.32 2015-11-27T17:33:00.417
my problem is
I want to display value instead of "1" in pickupName column. ( DineIn: 1, DriveThru: 2, TakeOut: 3).
show image in #imageindicaor column if pickupName ="DriveThru" otherwise hide the image.
show scheduledTime in custom format
if scheduledTime is current date then display as 12:15 pm.
if scheduled time is tomorrow date the display as 8/10 - 7:00am.
if pickupName ="TakeOut" then change that` row background color to gray and then remove that row after 2 minutes.
I want to display value instead of "1" in pickupName column. ( DineIn: 1, DriveThru: 2, TakeOut: 3).
Object.keys( objectName )[ propertyIndex ]
will return the desired property's name
The rest of your issues can be resolved with conditional statements once you've obtained the JSON data. You haven't provided your attempt so there isn't much to work with.
Hi for first point you need to write your enum properly numbers:"String" because you are getting numbers from JSON.
//Global Object
var pickupNameEnum = {
0: "DineIn",
1: "DriveThru",
2: "TakeOut"
};
Write a function as showRow(singleRowObject) in which while traversing your JSON
function showRow(singleRowObject){
var imageString="";
var hideImage=false;
var showString='';
var retutnObject={};
if(pickupNameEnum[singleRowObject.pickupType]!=undefiend){
showString='DineIn';
//DineIn
}else if(singleRowObject.pickupType==){
//DriveThru
showString='DriveThru';
imageString="<img src='abc.png' alt='img'></img>";
}else if(singleRowObject.pickupType==){
//TakeOut and change Color on basis of this flag
hideImage=true;
showString='TakeOut ';
}
retutnObject.hideImage=hideImage;
retutnObject.imageString=imageString;
retutnObject.showString=showString;
}
For date split dateString and refer to this question
For Removing Row change refer this

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

Categories