I am having a hard time retrieving data from json object - javascript

{
"formname": ["Myapname", {
"operation": ["add", {
"values": {
"confirm_code": "12345",
"ID": 222333333,
"user_id": "10000"
},
"status": "Success"
}]
}]
}
I have tried this below:
posting.done(function( data ) {
var obj = JSON.parse(data);
console.log(obj["ID"]);
});
});
But I am not getting back anything all I see undefined
can someone assist me with what am doing wrong

ID is not a property of obj, it's property of it's nested object. You can get it using obj.formname[1].operation[1].values.ID
var obj = {
"formname": ["Myapname", {
"operation": ["add", {
"values": {
"confirm_code": "12345",
"ID": 222333333,
"user_id": "10000"
},
"status": "Success"
}]
}]
};
console.log(
obj.formname[1].operation[1].values.ID
)

Related

vue filtering method how it works

Here's the some code i try what I did
deleteajobewith_events(event){
const data =event.store.readQuery({
query: ClientJobesList,
variables: {id:1}
});
data.client.jobes.filter(jobee=>jobee.id != 101);
console.log(data);
event.store.writeQuery({ query: ClientJobesList, data});
}
If I console log the 'data', it shows the same data without filtering
this is a hint about the 'data' object
{
"data": {
"client": {
"id": "1",
"client_name": "Marouane",
"jobes": [
{
"id": "101",
"title": "cbkvjk",
"order": 88,
"client_id": "1"
},
.........
]
}
}
}
Filter creates new array, and data must be the same type (101 is not the same as "101") so try like following:
const data= {
"client": {
"id": "1",
"client_name": "Marouane",
"jobes": [
{
"id": "101",
"title": "cbkvjk",
"order": 88,
"client_id": "1"
},
{
"id": "102",
"title": "aaa",
"order": 99,
"client_id": "2"
},
]
}
}
data.client.jobes = data.client.jobes.filter(jobee=>jobee.id !== '101');
console.log(data)
u haven't assign filtered data to previous one :
deleteajobewith_events(event){
const data =event.store.readQuery({
query: ClientJobesList,
variables: {id:1}
});
data.client.jobes = data.client.jobes.filter(jobee=>jobee.id != 101);
console.log(data);
event.store.writeQuery({ query: ClientJobesList,
data});
}

How to dynamically push an array using spread operator Javascript

[
{
"details": {
"name": "john",
"point": "20"
},
"list": {
"number": "30",
}
},
{
"details": {
"name": "doe",
"point": "25"
},
"list": {
"number": "30",
}
}
]
This is what i am trying to do, i am getting the data from the store and if the response is only one i use data = getData[0].details and if the response is more than one then i push the data using [...data, ...getData[1].details] if there are more than one data how can i achieve. thanks in advance
let data:any = [];
this.store
.pipe(
select(getData),
map((getData,i) => {
if (getData) {
data = [...data, ...getData[i].details]
}
return data;
})
)
I think you want to get an array of the details.
In this case you can say.
let data = [
{
"details": {
"name": "john",
"point": "20"
},
"list": {
"number": "30",
}
},
{
"details": {
"name": "doe",
"point": "25"
},
"list": {
"number": "30",
}
}
];
let details = data.map(a => a.details);
console.log(details);
I think i understand what you mean:
What I would do is map over your getData response and add to the original array on each iteration. It wont matter if there is 1 or many in the getData array:
getData.map(x => $data.push(x.details));

How to access an array of objects inside another array of objects in angular 4

I have a api response that return this :
{
"code": 0,
"message": "hierarchy list",
"payload": [
{
"id": 2,
"name": "nameParent",
"code": "WUcw",
"childsOfPayload": [
{
"id": 5,
"name": "NameChild1",
"code": "ozyW",
"status": "Active",
"childsofChildOfPayload": [
{
"id": 8,
"name": "NameChild2",
"code": "aitq",
"order": 30,
},
]}]}]}
I am trying to get the differents objects in each childs, ChildOfPayload and childOfChildOfpayload.
First I've returned the different name value of payload:
getAllPayloadName() {
this.userService.getName().subscribe(
data => {
this.values= data;
}
);
}
But what must I do to get the name of each child assosiated to the different parent value!
I mean in this case.
NameChild1
NameChild2
I've tried this:
manipulateDataa() {
this.values.subscribe(x => {
x.payload.foreach((y:any) => {
y.childs.foreach((z:any) => {
console.log( z.name)
})
})
})
}
then call it in getAllPayloadName, but still don't work. What could be wrong?
You could do something like this to get your desired output. Here you can read more about forEach loop which I have used.
data = {
"code": 0,
"message": "hierarchy list",
"payload": [
{
"id": 2,
"name": "nameParent",
"code": "WUcw",
"childsOfPayload": [
{
"id": 5,
"name": "NameChild1",
"code": "ozyW",
"status": "Active",
"childsofChildOfPayload": [
{
"id": 8,
"name": "NameChild2",
"code": "aitq",
"order": 30,
},
]}]}]}
names = []
function iterator (obj, namesArr){
Object.keys(obj).forEach(key => {
if(key === "name") {
namesArr.push(obj[key])
} else if(typeof obj[key] === "object") {
iterator(obj[key][0], names)
}
})
}
iterator(data.payload[0], names)
console.log(names)
if the api result structure is strongly type and will not change u can access the child payload name by this line
console.log(JSON.stringify(obj.payload[0].childsOfPayload[0].name));
console.log(JSON.stringify(obj.payload[0].childsOfPayload[0].childsofChildOfPayload[0].name));

Tableau Web Data Connector error

I am creating a Tableau Web Data Connector as per the documentation HERE.
I am running the Simulator and have setup a HTML page (as per tutorial) which calls a Javascript file that runs the Tableau WDC script as below.
(function () {
var myConnector = tableau.makeConnector();
myConnector.init = function(initCallback) {
initCallback();
tableau.submit();
};
myConnector.getSchema = function (schemaCallback) {
var cols = [
{ id : "date_of_work", alias : "Date of Work", dataType: tableau.dataTypeEnum.date },
{ id : "supervisor", alias : "Supervisor", dataType: tableau.dataTypeEnum.string }
];
var tableInfo = {
id : "test",
alias : "test",
columns : cols
};
schemaCallback([tableInfo]);
};
myConnector.getData = function (table, doneCallback) {
$.getJSON("http://myDataCall.php", function(response) {
// ERROR HERE!
var resp = response.job.job_workflows; // Response
var parsedResp = JSON.parse(resp); // Parse the response
var tableData = []; // Temp array
// Iterate over the JSON object
for (var i = 0, len = resp.length; i < len; i++) {
tableData.push({
"date_of_work": parsedResp[i]['job_status'],
"supervisor": parsedResp[i]['job_workflow_1197927'],
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
})();
When I run the script I get the error: The WDC reported an error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1 stack:SyntaxError:
Unexpected token o in JSON at position 1 at JSON.parse () at Object.success
The (abbreviated) JSON that is being returned looks as follows:
{
"employee": {
"id": 23940,
},
"company": {
"id": 1059,
},
"job": {
"id": 13712707,
"job_status_logs": [{
"id": 17330391,
}],
"company": {
"id": 1059,
},
"created_by": {
"id": 23940,
},
"job_workflows": [{
"id": 1087689283,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251218,
"name": "Date of work",
"action": "datepicker",
"optional": 0,
"action_values": "",
"action_value_entered": "2017-10-12",
"nested_workflow_id": 0,
}, {
"id": 1087689284,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251219,
"name": "Supervisor",
"action": "list",
"optional": 0,
"action_values": "John Doe",
"action_value_entered": "John Doe",
"nested_workflow_id": 0,
}],
"job_fields": [{
"id": 50456098,
}],
"job_status_change_messages": [{
"id": 59957985}],
"job_assets":[]
}
}
I am trying to access the job.job_workflows.action_value_entered value but keep getting the error as above.
How can I fix this error?
There are a couple of issues here.
1) The JSON sent back from your server is invalid. Here is the valid version. I recommend using a site like https://jsonformatter.curiousconcept.com/ to validate your JSON.
{
"employee": {
"id": 23940
},
"company": {
"id": 1059
},
"job": {
"id": 13712707,
"job_status_logs": [{
"id": 17330391
}],
"company": {
"id": 1059
},
"created_by": {
"id": 23940
},
"job_workflows": [{
"id": 1087689283,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251218,
"name": "Date of work",
"action": "datepicker",
"optional": 0,
"action_values": "",
"action_value_entered": "2017-10-12",
"nested_workflow_id": 0
}, {
"id": 1087689284,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251219,
"name": "Supervisor",
"action": "list",
"optional": 0,
"action_values": "John Doe",
"action_value_entered": "John Doe",
"nested_workflow_id": 0
}],
"job_fields": [{
"id": 50456098
}],
"job_status_change_messages": [{
"id": 59957985}],
"job_assets":[]
}
}
2) jQuery's getJson method returns an object, so you don't need to parse it. You can just use the resp variable directly like so:
var resp = response.job.job_workflows; // Response
var tableData = []; // Temp array
// Iterate over the JSON object
for (var i = 0, len = resp.length; i < len; i++) {
tableData.push({
"date_of_work": resp[i]['job_status'],
"supervisor": resp[i]['job_workflow_1197927'],
});
}
table.appendRows(tableData);
doneCallback();
Fixing those two issues should unblock you. However, you'll want to think through what data you are sending back. The current values you are sending back do not exist in the JSON (i.e. resp[i]['job_workflow_1197927']).
Instead, you could do something like this: resp[1].job_id, which would give you the job_id of each job_workflow.

How to segregate the JSON response I'm getting [duplicate]

This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 5 years ago.
{
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": "TimeStamp2"
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp2"
}
]
}
(Where TimeStamp1 andTimeStamp2 are valid time stamps)
I'm getting the above data using a Rest Service. I need to
Showcase it in a different manner. Have to convert it this way that I'll get the response in 2 variables called
Category = [TimeStamp1,TimeStamp2]
and
Data= [{
name: 'DB',
data: [100, 100]
}, {
name: 'Oracle',
data: [0, 100]
}]
Thanks in Advance
The first one is easy, just map the data array to one containing only the timestamps and pipe it into a Set
const Category = Array.from(new Set(obj.Data.map(datum => datum.TimeStamp)))
The second will require you to reduce the data to a map of Rsrc to a status array which you can then transform into an array
const obj = {"Data":[{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"0","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"100","TimeStamp":"TimeStamp2"},{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp2"}]}
const Data = Array.from(obj.Data.reduce((map, datum) => {
let data = map.get(datum.Rsrc) || []
return map.set(datum.Rsrc, data.concat(datum.status))
}, new Map())).map(entry => ({
name: entry[0],
data: entry[1]
}))
console.info('Data', Data)
var input ={
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": "TimeStamp2"
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp2"
}
]
};
var data= input.Data;
var Category =[];
var Data =[];
var DataIndex = [];
data.forEach(function(i)
{
if(Category.indexOf(i.TimeStamp)==-1) Category.push(i.TimeStamp);
var idx=DataIndex.indexOf(i.Rsrc)
if(idx==-1) {
DataIndex.push(i.Rsrc);
Data.push({name:i.Rsrc,data:[i.status]});
} else {
Data[idx].data.push(i.status);
}
});
console.log(Category);
console.log(Data);
I looped over your data and built the two new arrays. I used a third rsrc array to help to determine which position in the data array to add new items too.
var test = {
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": 'TimeStamp1'
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": 'TimeStamp1'
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": 'TimeStamp2'
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": 'TimeStamp2'
}
]
};
var category = [];
var data = [];
var rsrc = [];
test['Data'].forEach(function( item ){
if( category.indexOf( item['TimeStamp'] ) === -1 ){
category.push( item['TimeStamp'] );
}
if( rsrc.indexOf( item[ 'Rsrc' ] ) === -1 ){
rsrc.push( item[ 'Rsrc' ] );
}
var pos = rsrc.indexOf( item[ 'Rsrc' ] );
// set as itself or an object if it's not yet been set
data[pos] = data[pos] || {};
data[pos].name = item[ 'Rsrc' ];
data[pos].data = data[pos].data || [];
data[pos].data.push( item.status );
});
console.log( category );
console.log( data );
Edit fixed issue with repeated categories, thanks to #yashgarg1232

Categories

Resources