How To Get The Parent value from Json for this select2 - javascript

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

Related

Is it possible to print the label of the object instead the id in material ui DataGrid

So I have two tables in my database. I want a DataGrid UI to print all my columns except the categoryId I want to print a label instead (like in selection valueOptions) :
const columns: GridColDef = [
{
"field": "title",
"headerName": "Titel",
"width": 350,
"editable": true
},
{
"field": "categoryId",
"headerName": "Kategorie",
"width": 250,
"editable": true,
"type": "singleSelect",
"valueOptions": [
{
"value": "miv560972ynqzk9",
"label": "stuff 1"
},
{
"value": "1t7n08l9tfdwotn",
"label": "stuff 2"
},
]
}
]
const rows: GridRowsProp = [
{
"categoryId": "miv560972ynqzk9",
"title": "Lineare Algebra Hausaufga",
},
{
"categoryId": "1t7n08l9tfdwotn",
"title": "Test",
},
]
So I want something like this:
const rows: GridRowsProp = [
{
"categoryId": { value:"miv560972ynqzk9", label: "stuff1"},
"title": "Lineare Algebra Hausaufga",
},
{
"categoryId": { value: "1t7n08l9tfdwotn", label: "stuff2" },
"title": "Test",
},
]

How can I select children options from optgroup in Select2?

Question:
I have successfully created a select2 template with a group but I can't select the items in it, is there anything missing from the code I made below? Any help from you means a lot to me, thank you
See this first,
Preview Image
For the data below, i folow https://select2.org/data-sources/formats
Result from AJAX :
{
"status": true,
"message": null,
"data": [
{
"text": "Bank",
"children": [
{
"id": "002",
"icon": ".../payment/bri_1.png",
"text": "BANK BRI"
},
{
"id": "008",
"icon": ".../payment/mandiri_1.png",
"text": "BANK MANDIRI"
},
{
"id": "009",
"icon": ".../payment/bni_1.png",
"text": "BANK BNI / SYARIAH"
},
{
"id": "014",
"icon": ".../payment/bca_1.png",
"text": "BANK BCA"
},
{
"id": "022",
"icon": ".../payment/1280px-CIMB_Niaga_logo.svg.png",
"text": "CIMB NIAGA / SYARIAH"
},
{
"id": "016",
"icon": ".../payment/Maybank-Logo.png",
"text": "Maybank"
},
{
"id": "013",
"icon": ".../payment/images.png",
"text": "PERMATA BANK"
},
{
"id": "213",
"icon": ".../payment/Jenius-logo.png",
"text": "Jenius/BTPN"
},
{
"id": "011",
"icon": ".../payment/kissclipart-danamon-logo-png-clipart-bank-danamon-logo-a9b2b21755c37a3a.png",
"text": "Danamon"
},
{
"id": "012",
"icon": ".../payment/images_1.png",
"text": "Bank Neo Commerce/Bank Yudha Bakti"
},
{
"id": "017",
"icon": ".../payment/images-removebg-preview.png",
"text": "Bank Syariah Indonesia"
}
]
},
{
"text": "eMoney",
"children": [
{
"id": "900",
"icon": ".../payment/ovo.png",
"text": "OVO"
},
{
"id": "901",
"icon": ".../payment/gopay.png",
"text": "GOPAY"
},
{
"id": "903",
"icon": ".../payment/dana_1.png",
"text": "DANA"
},
{
"id": "904",
"icon": ".../payment/linkaja.png",
"text": "LINK AJA"
},
{
"id": "906",
"icon": ".../payment/shopeepay-shopee.co.id_ratio-16x9.jpg",
"text": "SHOPEE PAY"
}
]
}
]
}
Code :
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
minimumResultsForSearch: Infinity,
templateResult: function formatState(state) {
if (!state.id) return state.text;
var $state = $(
'<span><img src="' + state.icon + '" style="width:30px;"/> ' + state.text + '</span>'
);
return $state;
},
ajax: {
url: base_url + 'user/api/payment',
dataType: 'json',
processResults: function(data) {
return {
results: $.map(data.data, function(item, key) {
var children = [];
for (var k in item.children) {
var childItem = [];
childItem.id = item.children[k].id;
childItem.icon = item.children[k].icon;
childItem.text = item.children[k].text;
children.push(childItem);
}
return {
text: item.text,
children: children,
}
})
};
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Payment</label>
<div class="col-sm-10">
<select name="payment" id="payment" class="form-control">
</select>
</div>
</div>
As far as I can see in your code, your API is returning results already formatted, so keep it simple. Please check this fiddle with a fully working example based on your code.
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
ajax: {
url: 'https://randomuser.me/api/', //a random URL to simulate a request response in jsfiddle
dataType: 'json',
processResults: (data) => ({ results: response.data })
}
});

How to add object to specific place in JavaScript?

I am using a library React simple chatbot and add data from database, but the problem is i have array like below
Array from Database
[{
"id": 1,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"message": "What is your age?",
"type": "text",
"trigger": "3"
}, {
"id": 3,
"message": "What is your date of birth?",
"type": "text",
"trigger": "1"
}]
But i need something like below
[{
"id": 1,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"user": true,
"trigger": 3
}, {
"id": 3,
"message": "What is your age?",
"type": "text",
"trigger": "4"
}, {
"id": 4,
"user": true,
"trigger": 5
}, {
"id": 5,
"message": "What is your date of birth?",
"type": "text",
"trigger": "6"
}, {
"id": 6,
"user": true,
"trigger": 1
}]
Please help me to create array like this. I write some code, but doesn't work for me. My code print duplicate ids. Basically i want to pass object after every object with increment id.
Code
fetch("api_url_here")
.then((res) => {
return res.json();
})
.then((data) => {
const steps = data.map((res, index) => {
return {
id: index,
message: res.question,
type: res.type,
trigger: res.trigger,
};
});
var array = [];
var trigger = 1;
steps.forEach((step, index) => {
index = index;
array.push(step);
if (step.type == "text") {
array.push({
id: trigger + 1,
user: true,
trigger: trigger,
});
}
trigger++;
});
document.getElementById("json").append(JSON.stringify(array));
})
Current Output
[{
"id": 0,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"user": true,
"trigger": 1
}, {
"id": 1,
"message": "What is your age?",
"type": "text",
"trigger": "3"
}, {
"id": 3,
"user": true,
"trigger": 2
}, {
"id": 2,
"message": "What is your date of birth?",
"type": "text",
"trigger": "1"
}, {
"id": 4,
"user": true,
"trigger": 3
}]
Any solution appreciated!
You only need to add this as a final step to correct the id and trigger
const almost = [{
"id": 0,
"message": "What is your name?",
"type": "text",
"trigger": "2"
}, {
"id": 2,
"user": true,
"trigger": 1
}, {
"id": 1,
"message": "What is your age?",
"type": "text",
"trigger": "3"
}, {
"id": 3,
"user": true,
"trigger": 2
}, {
"id": 2,
"message": "What is your date of birth?",
"type": "text",
"trigger": "1"
}, {
"id": 4,
"user": true,
"trigger": 3
}]
const final = almost.map( (obj,index) => {
const newObj = {};
Object.assign(newObj,
obj,
{
"id":index+1,
"trigger": index+2
}
);
return newObj;
});
final[final.length-1].trigger = 1;
console.log(final)
EDIT: to make it clear, your code would look like:
fetch("api_url_here")
.then((res) => {
return res.json();
})
.then((data) => {
const steps = data.map((res, index) => {
return {
id: index,
message: res.question,
type: res.type,
trigger: res.trigger,
};
});
var array = [];
var trigger = 1;
steps.forEach((step, index) => {
index = index;
array.push(step);
if (step.type == "text") {
array.push({
id: trigger + 1,
user: true,
trigger: trigger,
});
}
trigger++;
});
array = array.map( (obj,index) => {
const newObj = {};
Object.assign(newObj,
obj,
{
"id":index+1,
"trigger": index+2
}
);
return newObj;
});
array[array.length-1].trigger = 1;
document.getElementById("json").append(JSON.stringify(array));
})

Toggle property of nested array of object - JS

I have an array of objects with 3 levels. I want to target the innermost child with property 'code'. If code is present, then update the child as well as the parent object with selected: true. If the property already is true, then sending in the same value should set the child to selected: false (toggle)
This is what I have going so far. If selected is true for a child, sending in another code should set selected: true for the corresponding child and selected: false for the child which had true for selected property.
Also, if selected is true for a child, defaultCollapsed property should be false for the child as well as parent and grandparent. Ifs elected is false for a child, defaultCollapsed property should be true for the child as well as parent and grandparent
const data = [{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": true,
"label": "Parent 1",
"selected": true,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
function select(items, key, value) {
if (!Array.isArray(items)) {
return false;
}
for (const item of items) {
if (item.code === value || select(item.items, key, value)) {
item.selected = !item.selected;
item.defaultCollapsed = false;
return true;
}
}
return false;
}
function reset(items) {
if (!Array.isArray(items)) {
return;
}
for (const item of items) {
if (item.selected) {
reset(item.items);
item.selected = false;
break;
}
}
}
function resetAndSelect(data, key, value) {
reset(data);
select(data, key, value);
}
resetAndSelect(data, 'code', 'CHILD_1')
console.log('CHILD_1',data)
resetAndSelect(data, 'code', 'CHILD_2')
console.log('CHILD_2',data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
If code is CHILD_1:
[{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"selected": true,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
"selected": true,
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": false,
"label": "Parent 1",
"selected": true,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
If the above output is the actual data, and the code is CHILD_1 again, I need to toggle the selected property of the child as well the corresponding parents.
[{
"label": "Grand Parent 1",
"index": 0,
"code": "GRAND_PARENT_1",
"defaultCollapsed": true,
"selected": false,
"items": [{
"id": 1,
"items": [{
"id": 100,
"label": "Child 1",
"url": "#CHILD_1",
"code": "CHILD_1",
"selected": false,
},
{
"id": 200,
"label": "Child 2",
"url": "#CHILD_2",
"code": "CHILD_2"
},
{
"id": 300,
"label": "Child 3",
"url": "#CHILD_3",
"code": "CHILD_3"
},
{
"id": 400,
"label": "Child 4",
"url": "#CHILD_4",
"code": "CHILD_4"
}
],
"defaultCollapsed": false,
"label": "Parent 1",
"selected": false,
},
{
"id": 2,
"items": [],
"defaultCollapsed": true,
"label": "Parent 2"
},
{
"id": 3,
"items": [],
"defaultCollapsed": true,
"label": "Parent 3"
},
{
"id": 4,
"items": [],
"defaultCollapsed": true,
"label": "Parent 4"
}
]
},
{
"label": "Grand Parent 2",
"index": 1,
"code": "GRAND_PARENT_2",
"defaultCollapsed": true,
"items": []
},
{
"label": "Grand Parent 3",
"index": 2,
"code": "GRAND_PARENT_3",
"defaultCollapsed": true,
"items": []
}
]
You can do this by creating recursive function using forEach loop and passing array of parents down with recursion so that you can update its selected property.
const data = [{"label":"Grand Parent 1","index":0,"code":"GRAND_PARENT_1","defaultCollapsed":true,"items":[{"id":1,"items":[{"id":100,"label":"Child 1","url":"#CHILD_1","code":"CHILD_1"},{"id":200,"label":"Child 2","url":"#CHILD_2","code":"CHILD_2"},{"id":300,"label":"Child 3","url":"#CHILD_3","code":"CHILD_3"},{"id":400,"label":"Child 4","url":"#CHILD_4","code":"CHILD_4"}],"defaultCollapsed":true,"label":"Parent 1","selected":true},{"id":2,"items":[],"defaultCollapsed":true,"label":"Parent 2"},{"id":3,"items":[],"defaultCollapsed":true,"label":"Parent 3"},{"id":4,"items":[],"defaultCollapsed":true,"label":"Parent 4"}]},{"label":"Grand Parent 2","index":1,"code":"GRAND_PARENT_2","defaultCollapsed":true,"items":[]},{"label":"Grand Parent 3","index":2,"code":"GRAND_PARENT_3","defaultCollapsed":true,"items":[]}]
function update(data, key, value, parents = []) {
data.forEach(e => {
if (e[key] === value) {
if (parents.length) {
e.selected = !e.selected;
parents.forEach(p => {
p.defaultCollapsed = !e.selected
p.selected = e.selected
})
data.forEach(s => {
if (s != e && s.selected) s.selected = false;
});
}
}
if (e.items && e.items.length) {
update(e.items, key, value, [...parents, e])
}
})
}
update(data, 'code', 'CHILD_4')
update(data, 'code', 'CHILD_4')
update(data, 'code', 'CHILD_2')
update(data, 'code', 'CHILD_1')
console.log(data)
You could toggle the target node and leave the rest as true, for the path to the item.
function update(array, value) {
var found = false;
array.forEach(o => {
var sub = update(o.items || [], value),
check = o.code === value;
if (check) {
o.selected = !o.selected
found = o.selected;
} else {
o.selected = sub;
if (sub) found = o.selected;
}
o.defaultCollapsed = !o.selected;
});
return found;
}
var data = [{ label: "Grand Parent 1", index: 0, code: "GRAND_PARENT_1", defaultCollapsed: true, items: [{ id: 1, items: [{ id: 100, label: "Child 1", url: "#CHILD_1", code: "CHILD_1" }, { id: 200, label: "Child 2", url: "#CHILD_2", code: "CHILD_2" }, { id: 300, label: "Child 3", url: "#CHILD_3", code: "CHILD_3" }, { id: 400, label: "Child 4", url: "#CHILD_4", code: "CHILD_4" }], defaultCollapsed: false, label: "Parent 1" }, { id: 2, items: [], defaultCollapsed: true, label: "Parent 2" }, { id: 3, items: [], defaultCollapsed: true, label: "Parent 3" }, { id: 4, items: [], defaultCollapsed: true, label: "Parent 4" }] }, { label: "Grand Parent 2", index: 1, code: "GRAND_PARENT_2", defaultCollapsed: true, items: [] }, { label: "Grand Parent 3", index: 2, code: "GRAND_PARENT_3", defaultCollapsed: true, items: [] }];
update(data, 'CHILD_1');
console.log(data);
update(data, 'CHILD_1');
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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