building json by using mysql fetch result - javascript

hello i want to use my mysql result to build the json objects. my first query is fetching parent menu and another query is fetching child menu so i am going to put my child menu result under the parent menu.. i want to know what is wrong with my code and how to correct
<?php
$selectparentMenu=mysql_query("SELECT `id`,`item_name`,`menu_type`,`parent` FROM `epic_master_menu` where parent=0");
//echo $myfetch=mysql_fetch_array($selectMenu);
if(mysql_num_rows($selectparentMenu)>1) {
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
//echo 'parent id is' .$parentId=$fetchparentMenu['id']. '<br/>';
// echo 'parent name is' .$parentId=$fetchparentMenu['item_name']. '<br/>';
$selectchildMenu=mysql_query("SELECT `id` , `item_name` , `menu_type` , `parent` FROM `epic_master_menu`
WHERE parent >0 AND `menu_type` = 'item' AND `parent` ='".$fetchparentMenu['id']."'");
if(mysql_num_rows($selectchildMenu)>1) {
while($fetchchildMenu=mysql_fetch_array($selectchildMenu)) {
$textjson = '{
"dataSource": [{
"id": "", "text": "Select All", "expanded": "true", "spriteCssClass": "rootfolder", "items": [
{
"id": "'.$fetchparentMenu["id"].'", "text": "'.$fetchparentMenu["item_name"].'", "expanded": true,"spriteCssClass": "folder", "items": [
{ "id": "'.$fetchchildMenu["id"].'", "text": "'.$fetchparentMenu["item_name"].'", "spriteCssClass": "html" },
{ "id": "'.$fetchchildMenu["id"].'", "text": "'.$fetchparentMenu["item_name"].'", "spriteCssClass": "html" },
{ "id": "'.$fetchchildMenu["id"].'", "text": "'.$fetchparentMenu["item_name"].'", "spriteCssClass": "image" }
]
}
]
}]
}';
} }
/* $fetchMenu['item_name'];
$fetchMenu['menu_type'];
$fetchMenu['parent'];*/
//print_r($fetchMenu);
} }
// my json data is
$textjson = '{
"dataSource": [{
"id": 1, "text": "My Documents", "expanded": "true", "spriteCssClass": "rootfolder", "items": [
{
"id": 2, "text": "Project", "expanded": true,"spriteCssClass": "folder", "items": [
{ "id": 3, "text": "about.html", "spriteCssClass": "html" },
{ "id": 4, "text": "index.html", "spriteCssClass": "html" },
{ "id": 5, "text": "logo.png", "spriteCssClass": "image" }
]
},
{
"id": 6, "text": "New Web Site", "expanded": true, "spriteCssClass": "folder", "items": [
{ "id": 7, "text": "mockup.jpg", "spriteCssClass": "image" },
{ "id": 8, "text": "Research.pdf", "spriteCssClass": "pdf" }
]
},
{
"id": 9, "text": "Reports", "expanded": true, "spriteCssClass": "folder", "items": [
{ "id": 10, "text": "February.pdf", "spriteCssClass": "pdf" },
{ "id": 11, "text": "March.pdf", "spriteCssClass": "pdf" },
{ "id": 12, "text": "April.pdf", "spriteCssClass": "pdf" }
]
}
]
}]
}';

Instead of creating your own version.. you could simply make use of json_encode()
while($fetchchildMenu=mysql_fetch_array($selectchildMenu))
{
$somearr[]=$fetchchildMenu;
}
$jsonData = json_encode($somearr);
echo $jsonData; //<---- Prints your JSON data

Its much easier to use the included json functions from PHP. Here you can use json_encode to create a json string from an array.
$childArray = array();
while($fetchchildMenu=mysql_fetch_array($selectchildMenu)) {
$childArray[] = array(
'id' => $fetchchildMenu['id'],
'text' => $fetchchildMenu['text']
);
}
$jsonDataChilds = json_encode($childArray);
echo $jsonDataChilds;

Related

How to structure and all data in the objective from Json at App script

The JSON data I am working on it. This is coming from Facebook ad API. This is being build for google data studio connector
{
"data": [
{
"adcreatives": {
"data": [
{
"actor_id": "8834759718540",
"id": "538"
}
]
},
"insights": {
"data": [
{
"ad_id": "34536578578",
"impressions": "89108",
"actions": [
{
"action_type": "comment",
"value": "02"
},
{
"action_type": "post",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-10T22:59:33+0600",
"id": "34536578578"
},
{
"adcreatives": {
"data": [
{
"actor_id": "7834759718970",
"id": "342"
}
]
},
"insights": {
"data": [
{
"ad_id": "238509545896206",
"impressions": "57803",
"actions": [
{
"action_type": "post_engagement",
"value": "2102"
},
{
"action_type": "page_engagement",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-11T22:59:33+0600",
"id": "238509545896206"
}
],
"paging": {
"cursors": {
"before": "dfgdfgdfgdfsdgdfgdfgdfgdfgdgdg",
"after": "yuyuyuyutyuytuyutytynfrgersggsgs"
}
}
}
Here is the JavaScript code I have used in google app script but it is showing error. I know it is totally wrong
var data = {data: parseData.data.map(({actions, ...rest}) => ({...rest,...Object.fromEntries(actions.map(({action_type, value}) =>[action_type, value]))}))};
console.log(data);
Output should be like the following way so that I can get all the data in objective
{
"data": [
{
"actor_id": "8834759718540",
"id": "538",
"ad_id": "34536578578",
"impressions": "89108",
"comment": "02",
"post": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10",
"created_time": "2022-06-10T22:59:33+0600"
},
{
"actor_id": "7834759718970",
"id": "342",
"ad_id": "238512373324806",
"impressions": "57803",
"post_engagement": "2102",
"page_engagement": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
"created_time": "2022-06-11T22:59:33+0600"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MQZDZD"
}
}
}
You can try the code below, but it only works if adcreatives.data and insights.data have only 1 element :
let part = data.data.map(item => ({
"actor_id": item.adcreatives.data.at(0).actor_id,
"id": item.adcreatives.data.at(0).id,
"ad_id": item.insights.data.at(0).ad_id,
"impressions": item.insights.data.at(0).impressions,
"comment": item.insights.data.at(0).actions.at(0).value,
"post": item.insights.data.at(0).actions.at(1).value,
"date_start": item.insights.data.at(0).date_start,
"date_stop": item.insights.data.at(0).date_stop,
"created_time": item.created_time
}));
let result = {
data: part,
paging: data.paging
}
console.log(result);

Finding ID in nested array of objects

I'm still new to recursive functions but I'm having trouble returning the object once found to a variable (currently searching based on ID). I've included a dataset below and what I have so far. The recursive function finds the correct matching item, but when it returns it, it just returns undefined to the variable. I have tried the solution here and also get the same problem I have where it just returns undefined instead of the object. Any help/pointers would be great!
const data = {
"navItems": [
{
"type": "directory",
"id" : 1,
"name": "Nav Title 1",
"children": [
{
"downloadUrl": "",
"content": "",
"id" : 2,
"type": "file",
"name": "File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 3,
"name": "File 2.pdf"
},
{
"type": "directory",
"name": "Sub Title 1",
"id" : 4,
"children": [
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 5,
"name": "Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 6,
"name": "Sub File 2.docx"
}
]
},
{
"type": "directory",
"name": "Sub Title 2",
"id" : 7,
"children": [
{
"type": "directory",
"id" : 8,
"name": "Sub Sub Title 1",
"children": [
{
"downloadUrl": "",
"id" : 9,
"content": "",
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id" : 10,
"name": "Sub Sub File 2.pdf"
}
]
},
{
"type": "directory",
"name": "Sub Sub Title 2",
"id" : 11,
"children": [
{
"downloadUrl": "",
"content": "",
"id" : 12,
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"id" : 13,
"type": "file",
"name": "Sub Sub File 2.pdf"
}
]
}
]
}
]
}
]
}
/* console.log(navigationConfig);*/
const searchNavItems = (navItem) => {
if (navItem.id == 10) {
console.log(navItem);
return navItem;
} else {
if (navItem.hasOwnProperty("children") && navItem.children.length > 0 && navItem.type == "directory") {
navItem.children.map(child => searchNavItems(child))
} else {
return false;
}
}
};
let dataItem = data.navItems.forEach((item => {
let nav = searchNavItems(item);
console.log(nav);
}))
console.log(dataItem)
in your fn there are couple of problems
when you are maping over children you are not returning the array of children
forEach does not return anything () => void, so you will need to create a new variable to hold that value
let dataItem;
data.navItems.forEach((item) => {
console.log(searchNavItems(item));
dataItem = searchNavItems(item);
});
hope this helps
Presented below is one possible way to achieve the desired objective.
Code Snippet
const mySearch = (needle, hayStack) => (
hayStack.some(({ id }) => id === needle)
? (
{children, ...rest} = hayStack.find(({ id }) => id === needle),
[{...rest}]
)
: hayStack.flatMap(
({ children = [] }) => mySearch(needle, children)
)
);
/* explanation of the above method
// method to search for element/s with given "id"
// finding "needle" (ie "id") in hayStack (ie, "array" of objects)
const mySearch = (needle, hayStack) => (
// check if needle exists in current array
hayStack.some(({ id }) => id === needle)
? ( // find the matching array elt, destructure to access
// "children" and "rest" props.
// send the props other than "children"
{children, ...rest} = hayStack.find(({ id }) => id === needle),
[{...rest}]
) // if needle is not present in current array
// try searching in the inner/nested "children" array
: hayStack.flatMap( // use ".flatMap()" to avoid nested return
// recursive call to "mySearch" with "children" as the hayStack
({ children = [] }) => mySearch(needle, children)
)
);
*/
const data = {
"navItems": [{
"type": "directory",
"id": 1,
"name": "Nav Title 1",
"children": [{
"downloadUrl": "",
"content": "",
"id": 2,
"type": "file",
"name": "File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 3,
"name": "File 2.pdf"
},
{
"type": "directory",
"name": "Sub Title 1",
"id": 4,
"children": [{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 5,
"name": "Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 6,
"name": "Sub File 2.docx"
}
]
},
{
"type": "directory",
"name": "Sub Title 2",
"id": 7,
"children": [{
"type": "directory",
"id": 8,
"name": "Sub Sub Title 1",
"children": [{
"downloadUrl": "",
"id": 9,
"content": "",
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"type": "file",
"id": 10,
"name": "Sub Sub File 2.pdf"
}
]
},
{
"type": "directory",
"name": "Sub Sub Title 2",
"id": 11,
"children": [{
"downloadUrl": "",
"content": "",
"id": 12,
"type": "file",
"name": "Sub Sub File 1.pdf"
},
{
"downloadUrl": "",
"content": "",
"id": 13,
"type": "file",
"name": "Sub Sub File 2.pdf"
}
]
}
]
}
]
}]
};
console.log(
'data for id: 10\n',
mySearch(10, data.navItems)?.[0]
);
console.log(
'data for id: 13\n',
mySearch(13, data.navItems)?.[0]
);
console.log(
'data for id: 9\n',
mySearch(9, data.navItems)?.[0]
);
console.log(
'data for id: 3\n',
mySearch(3, data.navItems)?.[0]
);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Explanation
Inline comments added to the snippet above.

How To Get The Parent value from Json for this select2

var preload_data = [{
"id": 2049,
"text": "style",
"children": [{
"id": "6906957ed912c883",
"text": "Country"
}, {
"id": "d239d844608fdbcf",
"text": "Christmas"
}]
}, {
"id": 0,
"text": "unassigned",
"children": [{
"id": "52d8e1e8d419bb61",
"text": "Punk"
}, {
"id": "88b9826121aeb89b",
"text": "Upbeat"
}, {
"id": "8485e6dd8e33fc50",
"text": "test arda"
}, {
"id": "da9fa55495a4a463",
"text": "test1"
}, {
"id": "feb1177719f4b5a4",
"text": "test arda 3"
}, {
"id": "64a2ae4ec2c0a1ef",
"text": "Feel Good"
}, {
"id": "2512f7946f660dc5",
"text": "Happy"
}, {
"id": "b1e7203207bd068f",
"text": "Love"
}, {
"id": "fb3a42b8abbf975a",
"text": "Reminiscent"
}, {
"id": "56d60aed1278c5a0",
"text": "Indie"
}, {
"id": "5733de46970ac503",
"text": "Rock"
}, {
"id": "801c33b478d1d5be",
"text": "Singer Songwriter"
}, {
"id": "ee4c6f5c12782bb9",
"text": "World"
}, {
"id": "4605140218eb9e52",
"text": "Reality"
}, {
"id": "92934140c305706e",
"text": "Pop"
}, {
"id": "f40f55db44dc0846",
"text": "Acoustic"
}, {
"id": "07b3c4640e84bfeb",
"text": "Folk"
}]
}]
and I want the output for dropdown list
Style:Christmas for example
this is the select2 code
$("#hidStyles").select2({
containerCssClass: 'styleContainer',
data: preload_data,
width: '100%',
allowClear: true,
multiple: true,
dropdownCssClass: 'select2-hidden',
placeholder: 'Please enter the name of style here to assign it to this album',
formatSelection: format1,
escapeMarkup : function(m) { return m;},
formatSearching: null
//formatSelection : format
});
and this is How I format the Json :
function format1(item) {
opt = $("#hidStyles").find(':selected');
sel = opt.text;
//og = opt.closest(".select2-results-dept-0").attr(".select2-result-label");
ogx = opt.text.data.text;
return ogx + ':' + item.text;
}
how can I get the value so that it's like style : christmas
https://jsfiddle.net/jna7ft1c/3/
I am sorry the jsfiddle I am not familiar with for making the front end, but mostly the code is like written there

Search a Javascript Object for the position of a specific ID? [duplicate]

This question already has answers here:
Find by key deep in a nested array
(21 answers)
Closed 4 years ago.
I have a Javascript object with lots of different sections. How can I search through all of the sections to find the position of a specific ID? The ID's that I am searching for are not in a specific location, and can be located in any of the tree branches.
For example, I am searching for this ID:
xobmnbjxg0g_1527269346261
And I am trying to output the position of that ID, which would be this:
app['structure'][0]['if-children'][0]['id']
My Javascript Object:
var app = {
"structure": [
{
"id": "0",
"type":"IF",
"parameters": [
{
"id": "xobmnbjxg0g_1527269346260",
"type": "field",
"value": "CV_TEST_SPOT1X"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children": [
{
"id": "xobmnbjxg0g_1527269346261",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children":[
],
"else-children":[
]
}
],
"else-children":[
{
"id": "xobmnbjxg0g_1527269346262",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children":[
{
"id":"xobmnbjxg0g_152726934626X"
}
],
"else-children":[
{
"id":"xobmnbjxg0g_152726934626Y"
}
]
}
]
},
{
"id": "xobmnbjxg0g_1527269346263",
"type":"IF",
"parameters": [
[
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
]
],
"if-children": [
{
"id": "xobmnbjxg0g_1527269346264",
"type":"IF",
"parameters": [
[
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
]
],
"if-children":[
{
"id": "xobmnbjxg0g_1527269346265",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
],
"if-children":[
{
"id":"xobmnbjxg0g_1527269346266"
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346267"
}
]
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346268"
}
]
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346269"
}
]
}
]
};
Interesting puzzle/question.
pretty sure there are some edge cases im missing but this seems to pass some tests.
function is(obj, type){
return Object.prototype.toString.call(obj) === `[object ${type}]`;
}
function findPosition(obj, mykey, myval, res){
if(is(obj, "Object")){
if(mykey in obj && obj[mykey] === myval){
res.tree.push(mykey);
res.found = true;
} else {
for( let key in obj){
if(res.found) break;
res.tree.push(key);
findPosition(obj[key], mykey, myval, res);
}
if(!res.found) res.tree.pop();
}
} else if(is(obj, "Array")){
for(let i = 0; i < obj.length; i++){
if(res.found) break;
res.tree.push(i);
findPosition(obj[i], mykey, myval, res);
}
if(!res.found) res.tree.pop();
} else {
res.tree.pop();
}
return res;
}
Usage and output
findPosition([{one: { two: [{id: [{id:'my'}]}]}}], "id", "mys", {tree:[], found: false})
> tree: Array(0), found: false}
findPosition([{one: { two: [{id: [{id:'my'}]}]}}], "id", "my", {tree:[], found: false})
> {found: true, tree: [0, "one", "two", 0, "id", 0, "id"]}
For finding if current obj you are iterating over is an Array you can also use Array.isArray

how to replace the value in an JSON array for a existing key?

In my application I have a ajax call and am getting the following response based on this am constructing the questions & answer section which I have included in the JSFiddle
var responseQuestions = {
"error": false,
"message": "Success",
"result": {
"Questions": [{
"Id": "131a",
"Text": "In what county do you live?",
"Answers": [{
"Id": "abc1",
"Text": "option1"
},
{
"Id": "abc2",
"Text": "option2"
},
{
"Id": "abc3",
"Text": "option3"
},
{
"Id": "abc4",
"Text": "option4"
},
{
"Id": "abc5",
"Text": "option5"
}
],
"SelectedAnswerId": null
},
{
"Id": "132a",
"Text": "Which zip code has ever been a part of your address?",
"Answers": [{
"Id": "def1",
"Text": "option1"
},
{
"Id": "def2",
"Text": "option2"
},
{
"Id": "def3",
"Text": "option3"
},
{
"Id": "def4",
"Text": "option4"
},
{
"Id": "def5",
"Text": "option5"
}
],
"SelectedAnswerId": null
},
{
"Id": "133a",
"Text": "What was the original amount of your most recent mortgage?",
"Answers": [{
"Id": "ghi1",
"Text": "option1"
},
{
"Id": "ghi2",
"Text": "option2"
},
{
"Id": "ghi3",
"Text": "option3"
},
{
"Id": "ghi4",
"Text": "option4"
},
{
"Id": "ghi5",
"Text": "option5"
}
],
"SelectedAnswerId": null
}
]
}
};
Required Format:
var responseQuestions = {
"error": false,
"message": "Success",
"result": {
"Questions": [{
"Id": "131a",
"Text": "In what county do you live?",
"Answers": [{
"Id": "abc1",
"Text": "option1"
},
{
"Id": "abc2",
"Text": "option2"
},
{
"Id": "abc3",
"Text": "option3"
},
{
"Id": "abc4",
"Text": "option4"
},
{
"Id": "abc5",
"Text": "option5"
}
],
**"SelectedAnswerId": "abc2"**
},
{
"Id": "132a",
"Text": "Which zip code has ever been a part of your address?",
"Answers": [{
"Id": "def1",
"Text": "option1"
},
{
"Id": "def2",
"Text": "option2"
},
{
"Id": "def3",
"Text": "option3"
},
{
"Id": "def4",
"Text": "option4"
},
{
"Id": "def5",
"Text": "option5"
}
],
**"SelectedAnswerId": "def1"**
},
{
"Id": "133a",
"Text": "What was the original amount of your most recent mortgage?",
"Answers": [{
"Id": "ghi1",
"Text": "option1"
},
{
"Id": "ghi2",
"Text": "option2"
},
{
"Id": "ghi3",
"Text": "option3"
},
{
"Id": "ghi4",
"Text": "option4"
},
{
"Id": "ghi5",
"Text": "option5"
}
],
**"SelectedAnswerId": "ghi2"**
}
]
}
};
Now I need to submit this answer with the same above mentioned format along the "SelectedAnswerId" value(in the above mentioned array "SelectedAnswerId" is null and now I have to include the original selected ans Id based on questions ).
I have tried to fetch all the selected ans id in a array and attached the same in jsfiddle but am unable to proceed on how to append this ans id in the existing array based on questions. How to achieve this ?
Try the following loops:
$('input[type="radio"]:checked').each(function() {
var questionId = $(this).closest('.radioGroup').prev().attr('id');//get the question id
var answerId = this.id;//get the answer id
$.each(responseQuestions.result.Questions, function(i, v) {//loop each question
if (v.Id == questionId) {
$.each(v.Answers, function(ind, val) {//loop each answer
if (val.Id == answerId) {
responseQuestions.result.Questions[i]['SelectedAnswerId'] = answerId;//save the answer
}
});
}
});
});
console.log(responseQuestions);
demo:https://jsfiddle.net/mj3gvd5e/1/
Note: you need to change your question id to remove or add the a to be consistent both in the page and in the json
You have to find index based on question id and then set answerid at specific index
var index = responseQuestions.result.Questions.findIndex(function(val){
return val.Id === yourQuestionid;
})
responseQuestions.result.Questions[index].SelectedAnswerId = youranswerID;
First of all you need to have your main question id and Ans id into same array as given fiddle by Madalin jsfiddle.net/6q9mct68
second you get this array, you can loop through your first array and replace the string by compairing Id,

Categories

Resources