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
Related
JSON Object:
{
"students_detail": [
{
"student_id": 1,
"name": "abc",
"roll_number": 10
},
{
"student_id": 2,
"name": "pqr",
"roll_number": 12
}
],
"subject_details": [
{
"subject_id": 1,
"subject_name": "math"
},
{
"subject_id": 2,
"subject_name": "english"
}
],
"exam_details": [
{
"exam_id": 1,
"exam_name": "Prelim"
}
],
"mark_details": [
{
"id": 1,
"exam_id": 1,
"subject_id": 1,
"student_id": 1,
"mark": 51
},
{
"id": 2,
"exam_id": 1,
"subject_id": 2,
"student_id": 2,
"mark": 61
}
]
}
Ouptut:
{
"student_mark_details": [
{
"abc": {
"roll_number": 10,
"Prelim": [
{
"subject_name": "math",
"mark": 51
}
]
},
"pqr": {
"roll_number": 12,
"Prelim": [
{
"subject_name": "english",
"mark": 61
}
]
}
}
]
}
i tried using loops and accesing student_id in both object and comparing them but code gets too messy and complex,is there any way i can use map() or filter() in this or any other method.
i have no idea where to start,my brain is fried i know im asking lot but help will be appreciated (any link/source where i can learn this is fine too)
Your output object really has a weird format: student_mark_details is an array of size 1 that contains an object that has all your students in it. Anyway, this should give you what you need. It is a format that you find often because it is a system with primary key and secondary key used a lot in databases.
The key to manage that is to start with what is at the core of what you are looking for (here, you want to describe students, so you should start from there), and then navigate the informations you need by using the primary/secondary keys. In JS, you can use the find() function in the case where one secondary key can be linked only to one primary key (ex: one mark is linked to one exam), and the filter() function when a secondary key can be linked to multiple secondary keys (ex: a student is linked to many grades).
I am not sure if this is 100% what you need because there are maybe some rules that are not shown in your example, but it solves the problem you submitted here. You might have to test it and change it depending of those rules. I don't know what your level is so I commented a lot
const data = {
"students_detail": [
{
"student_id": 1,
"name": "abc",
"roll_number": 10
},
{
"student_id": 2,
"name": "pqr",
"roll_number": 12
}
],
"subject_details": [
{
"subject_id": 1,
"subject_name": "math"
},
{
"subject_id": 2,
"subject_name": "english"
}
],
"exam_details": [
{
"exam_id": 1,
"exam_name": "Prelim"
}
],
"mark_details": [
{
"id": 1,
"exam_id": 1,
"subject_id": 1,
"student_id": 1,
"mark": 51
},
{
"id": 2,
"exam_id": 1,
"subject_id": 2,
"student_id": 2,
"mark": 61
}
]
}
function format(data) {
const output = {
"student_mark_details": [{}]
};
//I start by looping over the students_detail because in the output we want a sumary by student
data.students_detail.forEach(student => {
//Initialization of an object for a particular student
const individualStudentOutput = {}
const studentId = student.student_id;
const studentName = student.name;
//The rollNumber is easy to get
individualStudentOutput.roll_number = student.roll_number;
//We then want to find the exams that are linked to our student. We do not have that link directly, but we know that our student is linked to some marks
//Finds all the marks that correspond to the student
const studentMarkDetails = data.mark_details.filter(mark => mark.id === studentId);
studentMarkDetails.forEach(individualMark => {
//Finds the exam that corresponds to our mark
const examDetail = data.exam_details.find(exam => individualMark.exam_id === exam.exam_id);
//Finds the subject that corresponds to our mark
const subjectDetail = data.subject_details.find(subject => individualMark.subject_id === subject.subject_id);
//We then create a grade that we will add to our exam
const grade = {
subject_name: subjectDetail.subject_name,
mark: individualMark.mark
}
//We then want to add our grade to our exam, but we don't know if our output has already have an array to represent our exam
//So in the case where it does not exist, we create one
if (!individualStudentOutput[examDetail.exam_name]) {
individualStudentOutput[examDetail.exam_name] = [];
}
//We then add our grade to the exam
individualStudentOutput[examDetail.exam_name].push(grade);
});
//Now that we have finished our individual output for a student, we add it to our object
output.student_mark_details[0][studentName] = individualStudentOutput;
})
return output;
}
console.log(JSON.stringify(format(data)))
Im trying to take JSON data and pass it into my 'HistoryChart' Component to try and map the dates and prices into two arrays so that I can present them on my chart. However, I keep getting undefined errors.
Here is the JSON Data:
{
"_id": 1,
"name": "",
"brand": "",
"image": "",
"sources": [],
"history": [
{
"_id": 3,
"price": "299.99",
"product": 1,
"date": "2021-07-01"
},
{
"_id": 4,
"price": "399.99",
"product": 1,
"date": "2021-07-08"
},
{
"_id": 5,
"price": "499.99",
"product": 1,
"date": "2021-07-15"
},
{
"_id": 6,
"price": "599.99",
"product": 1,
"date": "2021-07-22"
},
{
"_id": 7,
"price": "699.99",
"product": 1,
"date": "2021-07-29"
}
]
}
Here is my HistoryChart Component:
function HistoryChart({product}) {
var dates = product.history.map(function(e){ //<-- The Problem lies here where it says cannot map undefined.
return e.date;
});
var prices = product.history.map(function(e){
return e.price;
});
return (
<div>
<Line
data={{
labels: dates,
datasets: [{
label: `Average Price History (ID: ${product._id})`, //<-- This part works
backgroundColor:/* 'transparent' */ '#00ad0e',
borderColor: '#00ad0e',
data: prices,
}]
}}
width={100}
height={50}
options={{ maintainAspectRatio: true }}
/>
</div>
)
}
I am also using redux to get the Data:
const productDetails = useSelector(state => state.productDetails)
const {error, loading, product} = productDetails
And the data is passed into the HistoryChart Component like this:
<HistoryChart product={product}/>
Any Help would be Much appreciated, Thanks.
Sorry if this is not your principal problem, but same time when .map resulting in undefined the most simple adjust is verify if your array is undefined.
So in my projects i always check first if array is undefined, i will use your code to do a example
function HistoryChart({product}) {
if (product !== undefined){
var dates = product.history.map(function(e){
return e.date;
});
var prices = product.history.map(function(e){
return e.price;
});
}
Try this aproach and let me know if this work.
Cause of Error
As the data come from server, it take some time to load. and you get the undefine error because 1st time you want to access history of object product which is not yet loaded successfully.
Solution
const price = product && product.history.map(//do what you want)
use key values of object this way not cause any error because if product is not loaded it does'nt call map function and when product object loaded successfully it will call map function
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);
I'm trying to extract "translations" Array "text" and "verses" array "verse_key" data from below json response using Alamofire and swift3.
{
"verses": [
{
"id": 1,
"verse_number": 1,
"chapter_id": 1,
"verse_key": "1:1",
"text_madani": "بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ",
"text_indopak": "بِسْمِ اللّٰهِ الرَّحْمٰنِ الرَّحِيْمِ",
"text_simple": "بسم الله الرحمن الرحيم",
"juz_number": 1,
"hizb_number": 1,
"rub_number": 1,
"sajdah": null,
"sajdah_number": null,
"page_number": 1,
"audio": {
"url": "versesAbdulBaset/Mujawwad/mp3/001001.mp3",
"duration": 6,
],
"format": "mp3"
},
"translations": [
{
"id": 102574,
"language_name": "english",
"text": "In the name of Allah, the Beneficent, the Merciful.",
"resource_name": "Shakir",
"resource_id": 21
}
],
}
],
"meta": {
"current_page": 1,
"next_page": null,
"prev_page": null,
"total_pages": 1,
"total_count": 7
}
}
I'm new to swift and I can't find a way to achieve this. How can I get the values of "translations" Array "text" and "verses" array "verse_key" ?
thanks advance
Use swiftyJSON.
switch response.result{
case .success(let data) :
let json = JSON(data)
let verses = json["verses"].Stringvalue
print(verses) //get all verses
print(verses["verse_key"].Stringvalue) // get "verse_key"
break
You can take each values from this json by giving the key names. If you want to get the "verses" , use json["verses"].You can also use JSONdecoder.
I try to combine 2 tables of database to a json object, I think it is maybe a 3D array
like this↓
table_1 ->(name:"Ken"),(gender:"male")
table_2 ->(name:"Lon"),(gender:"male")
table_1 and 2 is 1st dimension, name and gender is 2nd dimension,
ken and male is 3rd dimension
so, I made a json object wiht PHP "json_encode()", and try to parse it with javascript
json object:
{
"client_infos":[ {
"client": {
"no": 1, "C_name": "ken", "input_date": "2017-07-20 13:44:46", "total_price": 123
}
,
"item_lists":[["item_list",
{
"no": 1, "rs_no": 1, "item_name": "ApplePie", "item_quantity": 2, "unit_price": 10
}
],
["item_list",
{
"no": 2, "rs_no": 1, "item_name": "BananaCow", "item_quantity": 3, "unit_price": 5
}
]]
}
,
{
"client": {
"no": 3, "C_name": "ken", "input_date": "2017-07-20 14:24:26", "total_price": 200
}
,
"item_lists":[["item_list",
{
"no": 5, "rs_no": 3, "item_name": "LimeMilk", "item_quantity": 5, "unit_price": 33
}
]]
}
]
}
how do I parse it ?
for example, I want to extract the data of 2nd client and item_lists.
I have been using JSON.parse(json), but I have no idea how to get the value.
var content = JSON.parse(res);
console.log(content.client_infos.client[1].no);
it's not work.
var object = JSON.parse(variableOrStringLiteral);
finally, I find out the right way to get the value that like this
var obj = JSON.parse(content);
obj.client_infos[0].client.no;