Send chained select values in email - javascript

I'm making a chained select dropdown list and I want the values witch are chosen to be exported to my main app, through email or somehow. I'm not sure what is the best solution. Here is the code example
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery.chained.js"></script>
<script type="text/javascript"></script>
<select id="year" name="year">
<option value= "">Step 1 - Select Year</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
</select>
<select id="model" name="model">
<option value="">Step 2 - Select Model</option>
<option value="80" class="1990 1991 1992">80</option>
</select>
<select id="engine" name="engine">
<option value="">Step 3 - Select Engine</option>
<option value="v10" class="80">v10</option>
</select>
<input id="button1" type="button" value="send!" />
<script src="jquery.chained.js" type="text/javascript"></script>
<script type="text/javascript">
$("#model").chained("#year")
$("#engine").chained("#model")
$(document).ready(function (){
$('#button1').click(function (){
alert($(':selected').text());
</script>
The alert is showing the selected options, but i need to export that text somehow so i can send it like a newsletter to my app.
If anyone can tell me what is the best way to do that i will be grateful and sorry if i didn't explain it good or if you can't understand what i mean.

Try this,
(function($) {
$.fn.cDropdown = function(x) {
return this.each(function() {
var wrapper = $(this);
var xx = $.extend({
obj: "",
}, x || {});
var lastCreated;
function initialized() {
var returnedData
$.grep(xx.obj, function(element, index) {
$.each(element, function(e, i) {
if (hasValue(i, "Primary", true)) {
returnedData = hasValue(i, "Primary", true);
return false;
}
})
});
initFirst(returnedData);
creator(xx.obj, returnedData)
clicker(returnedData);
runOrder(returnedData["Id"]);
}
function clicker(obj) {
var selector = obj["Id"] != null ? "#" + obj["Id"] : obj["Name"] != null ? "[Name=\"" + obj["Name"] + "\"]" : ""
$('body').on('change', selector, function() {
var se = $(selector).find('option[value="CPreQVa"]');
if (se.val() != $(this).find('option:selected').val()) {
var target = $(this).attr("class").split("cTrig_")[1];
var v = $(this).find('option:selected').val();
var d;
if ($('#' + target).is('[class*="cTrig_"]')) {
hideFollow($('#' + target))
}
$.each(xx.obj[0], function(i, o) {
if (hasValue(o, "Id", target) != null) {
d = hasValue(o, "Id", target);
return false;
}
});
$('#' + target).find('option').remove();
if (d != null) {
$.each(d["option"], function(i, o) {
var ot = "" + o["trigger"];
if (ot.indexOf(",") != -1) {
var arrot = ot.split(',');
$.each(arrot, function(ii, oo) {
if (v == oo || o["preSelect"] == true) {
$('#' + target).append($("<option></option>")
.attr("value", o["val"])
.text(o["text"]));
return false;
}
})
} else {
if (v == o["trigger"] || o["preSelect"] == true) {
$('#' + target).append($("<option></option>")
.attr("value", o["val"])
.text(o["text"]));
}
}
})
if (d["Sort"] != null && d["Sort"] === true) {
var options = $('#' + target).find("option");
var arr = options.map(function(_, o) {
return {
t: $(o).text(),
v: o.value
};
}).get();
arr.sort(function(o1, o2) {
return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
});
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
}
var t;
$.each(d["option"], function(i, o) {
t = hasValue(o, "preSelect", true)
return false;
})
if (t != null) {
$('#' + target).find('option[value="CPreQVa"]').prependTo($('#' + target)).attr("selected", true)
}
$('#' + target).show();
var q;
$.each(xx.obj[0], function(i, o) {
if (hasValue(o, "Id", obj["Child"])) {
q = hasValue(o, "Id", obj["Child"]);
return false;
}
})
if (q != null) {
if (q["Child"] != null) {
clicker(q);
}
}
}
} else {
var target = $(this).attr("class").split("cTrig_")[1]
if ($('#' + target).is('[class*="cTrig_"]')) {
hideFollow($('#' + target))
}
$('#' + target).hide();
}
})
};
function hideFollow(obj) {
var target = $(obj).attr("class").split("cTrig_")[1]
if ($('#' + target).is('[class*="cTrig_"]')) {
hideFollow($('#' + target))
}
$('#' + target).hide();
};
function initFirst(obj) {
if (obj["Id"] != null)
wrapper.attr("Id", obj["Id"])
if (obj["Name"] != null)
wrapper.attr("Name", obj["Name"])
if (obj["Class"] != null)
wrapper.addClass(obj["Class"] + " cTrig_" + obj["Child"])
$.each(obj["option"], function(e, i) {
wrapper.append($("<option></option>")
.attr("value", i["val"])
.text(i["text"]));
})
if (obj["Required"] != null)
wrapper.prop('required', true);
if (obj["Sort"] != null && obj["Sort"] === true) {
var options = wrapper.find("option");
var arr = options.map(function(_, o) {
return {
t: $(o).text(),
v: o.value
};
}).get();
arr.sort(function(o1, o2) {
return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0;
});
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
}
var t;
$.each(obj["option"], function(i, o) {
t = hasValue(o, "preSelect", true)
return false;
})
if (t != null) {
//$('#MyNiceList option[value="my_option_2"]').insertBefore('#MyNiceList option[value="my_option_1"]');
wrapper.find('option[value="CPreQVa"]').prependTo(wrapper).attr("selected", true)
}
};
function hasValue(o, key, value) {
if (o.hasOwnProperty(key) && o[key] === value)
return o;
};
function creator(ob, fo) {
$.each(ob[0], function(i, o) {
if (o["Id"] != fo["Id"]) {
var sel = $('<select>')
if (o["Id"] != null)
sel.attr("Id", o["Id"])
if (o["Name"] != null)
sel.attr("Name", o["Name"])
if (o["Class"] != null)
sel.addClass(o["Class"])
if (o["Required"] != null)
sel.prop('required', true);
if (o["Child"] != null)
sel.addClass("cTrig_" + o["Child"])
//if (lastCreated == null) {
// sel.hide().insertAfter(wrapper)
// lastCreated = "#" + o["Id"];
//} else {
// sel.hide().insertAfter($(lastCreated))
//}
sel.hide()
wrapper.after(sel)
}
})
};
function runOrder(id) {
var obj;
if ($('#' + id).is('[class*="cTrig_"]')) {
obj = $('#' + id).attr("class").split("cTrig_")[1]
$('#' + id).after($('#' + obj))
runOrder(obj);
}
};
initialized();
});
};
}(jQuery));
$('#cDropdown').cDropdown({
obj: [{
"year": {
"Id": "year",
"Name": "year",
"Primary": true,
"Class": "form-control",
"Child": "Model",
"Sort": true,
"Required": true,
"option": [{
"val": "CPreQVa",
"text": "Step 1 - Select Year",
"preSelect": true
}, {
"val": "1990",
"text": "1990"
}, {
"val": "1991",
"text": "1991"
}, {
"val": "1992",
"text": "1992"
}]
},
"Model": {
"Id": "Model",
"Name": "Model",
"Class": "form-control",
"Child": "Engine",
"Sort": true,
"option": [{
"val": "CPreQVa",
"text": "Step 2 - select Model",
"preSelect": true
}, {
"val": "80",
"text": "80",
"trigger": "1990"
}, {
"val": "80",
"text": "80",
"trigger": "1991"
}, {
"val": "80",
"text": "80",
"trigger": "1992"
}]
},
"Engine": {
"Id": "Engine",
"Name": "Engine",
"Class": "form-control",
"Sort": true,
"option": [{
"val": "CPreQVa",
"text": "Step 3 - Select Engine",
"preSelect": true
}, {
"val": "v10",
"text": "v10",
"trigger": "80"
}]
}
}]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cDropdown"></select>

Related

I have json formated time slots and want to convert in proper time slots as written description

I have below JSON output from nodejs which is listed as below:
`{
"data": {
"2018-08-21": [
{ "available_slots": [
{ "slots": "1.15" },
{ "slots": "2:45,3:45" },
{ "slots": "4:30,5:30,6:30,7:30,8:30,9:30,10:30,11:30" }
]
}
]
}
}`
And I want below output using nodejs:
`{ "available_slots":
[ {
"slot1": "2:45-3:45",
"slot2": "4:30-5:30",
"slot3": "5:30-6:30",
"slot4": "6:30-7:30" }
]
}`
I have coded below function to retrieve the above output but it gives only one slot data
function divideIntoSlots(slots) {
var mainSlots = {
"available_slots" :
[
{ "slot1" : "", "slot2" : "", "slot3" : "", "slot4" : ""
} ]
};
var i = 1;
slots.available_slots.forEach( function(slot) {
var mainS = slot.slots;
if(mainS.indexOf(',') > -1) {
mainS = mainS.split(',');
var newMain;
if(i==1){
newMain = mainS[0]+"-"+mainS[1];
mainSlots.available_slots[0].slot1 = newMain;
}
i++;
}
});
return mainSlots;
}
divideIntoSlots(slots)
OutPut:
`{ "available_slots":
[ {
"slot1": "2:45-3:45",
"slot2": "",
"slot3": "",
"slot4": "" }
]
}`
Anyone, please help me to short out this issue to resolve.
You can use reduce to summarise your data. Use forEach to loop thru the array,
var data = {"data":{"2018-08-21":[{"available_slots":[{"slots":"1.15"},{"slots":"2:45,3:45"},{"slots":"4:30,5:30,6:30,7:30,8:30,9:30,10:30,11:30"}]}]}}
function divideIntoSlots(slots) {
var mainSlots = {"available_slots": []};
var s = slots.available_slots.reduce((c, v) => {
v.slots.split(',').forEach((o, i, a) => {
if (c.length < 4 && a[i + 1]) c.push(o + "-" + a[i + 1]);
});
return c;
}, []).reduce((c, v, i) => Object.assign(c, {["slot" + (i + 1)]: v}), {});
mainSlots.available_slots.push(s);
return mainSlots;
}
var result = divideIntoSlots(data.data['2018-08-21'][0])
console.log(result);
Probably you want that:
function divideIntoSlots(slots) {
var mainSlots = {
"available_slots": [{
"slot1": "",
"slot2": "",
"slot3": "",
"slot4": ""
}]
};
let i = 1;
slots.available_slots.forEach(function(slot) {
var mainS = slot.slots;
if (mainS.indexOf(',') > -1 && mainSlots.available_slots[0].hasOwnProperty('slot' + i)) {
var newSlots = mainS.replace(/(\d+:\d+),(\d+:\d+)/g, "$1-$2")
newSlots = newSlots.split(",");
if (newSlots.length > 1) {
newSlots.forEach(e => {
if (!mainSlots.available_slots[0].hasOwnProperty("slot" + i))
return;
mainSlots.available_slots[0]["slot" + i] = e;
i++;
});
} else {
mainSlots.available_slots[0]["slot" + i] = newSlots[0];
i++
}
}
});
return mainSlots;
}
console.log(divideIntoSlots({
"available_slots": [{
"slots": "1:15"
},
{
"slots": "2:45,3:45"
},
{
"slots": "4:30,5:30,6:30,7:30,8:30,9:30,10:30,11:30"
}
]
}));

How to convert multiple dimension list into one dimension list

If I have this JSON data that is from the original file.
[{"food": {"spicy": "spicy","sweet": "sweet"},
"water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}, {"food": {"spicy": "spicy","sweet": "sweet"},
"water": {"sweet": "sweet","sour": {"cold": "ice lemon","hot": "lemon tea"}}
}]
how do I convert into a one-dimensional list like this?
[{
"food-spicy": "spicy",
"food-sweet ": "sweet",
"water-sweet ": "sweet",
"water-sour-cold ": "ice lemon",
"water-sour-hot ": "lemon tea"
}, {
"food-spicy": "spicy",
"food-sweet ": "sweet",
"water-sweet ": "sweet",
"water-sour-cold ": "ice lemon",
"water-sour-hot ": "lemon tea"
}]
Please help.
You could write a function that flatten an object recursively. Then map the array using that function:
function flatten(oldObj) {
return Object.keys(oldObj).reduce(function(newObj, oldKey) { // for each key "oldKey" in oldObj
var value = oldObj[oldKey]; // get the value of the current oldKey from oldObj
if(value && typeof(value) === "object") { // if the value is also an object (add "&& !Array.isArray(value)" to exclude arrays)
value = flatten(value); // then flatten it first
Object.keys(value).forEach(function(key) { // and for each key in the new flattened value object
newObj[oldKey + "-" + key] = value[key]; // add a key-value to newObj where key is "oldKey-key" and the value is value[key]
});
} else {
newObj[oldKey] = value; // otherwise (if the value is not an object), just copy the key-value to newObj as it is
}
return newObj;
}, {});
}
Then use it like this:
var newArray = oldArray.map(flatten);
Example:
function flatten(oldObj) {
return Object.keys(oldObj).reduce(function(newObj, oldKey) {
var value = oldObj[oldKey];
if(value && typeof(value) === "object") {
value = flatten(value);
Object.keys(value).forEach(function(key) {
newObj[oldKey + "-" + key] = value[key];
});
} else {
newObj[oldKey] = value;
}
return newObj;
}, {});
}
var oldArray = [{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}},{"food":{"spicy":"spicy","sweet":"sweet"},"water":{"sweet":"sweet","sour":{"cold":"ice lemon","hot":"lemon tea"}}}];
var newArray = oldArray.map(flatten);
console.log(newArray);
try this:
var data = [{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
},
{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
}
]
var res = data.map(obj => {
return Reflect.ownKeys(obj).reduce((re, key) => {
Reflect.ownKeys(obj[key]).reduce((r, k) => {
if (typeof obj[key][k] === 'object') {
Reflect.ownKeys(obj[key][k]).reduce((r2, k2) => {
r2[key + '-' + k + '-' + k2] = obj[key][k][k2]
return r2
}, r)
} else {
r[key + '-' + k] = obj[key][k]
return r
}
}, re)
return re
}, {})
})
console.log(res)
And here is a more universal version which applicable for more nested obj
var data = [{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
},
{
food: {
spicy: 'spicy',
sweet: 'sweet'
},
water: {
sweet: 'sweet',
sour: {
cold: 'ice lemon',
hot: 'lemon tea'
}
}
}
]
function customReduce(obj, subObj, lastReduceObj = {}, lastKey = '') {
let res = Reflect.ownKeys(subObj).reduce((re, key) => {
if (lastKey === '') {
customReduce(obj, obj[key], re, key)
} else if (typeof subObj[key] === 'object') {
customReduce(obj, subObj[key], re, lastKey + '-' + key)
} else {
re[lastKey + '-' + key] = subObj[key]
}
return re
}, lastReduceObj)
return res
}
var res = data.map(obj => {
return customReduce(obj, obj)
})
console.log(res)
Try this :
var jsonObj = [{
"food": {
"spicy": "spicy",
"sweet": "sweet"
},
"water": {
"sweet": "sweet",
"sour": {
"cold": "ice lemon",
"hot": "lemon tea"
}
}
}, {
"food": {
"spicy": "spicy",
"sweet": "sweet"
},
"water": {
"sweet": "sweet",
"sour": {
"cold": "ice lemon",
"hot": "lemon tea"
}
}
}];
var newObj = {};
for (var i in jsonObj) {
for (var j in Object.keys(jsonObj[i])) {
for (var k in Object.keys(jsonObj[i])[j]) {
newObj[Object.keys(jsonObj[i])[j]+'-'+Object.keys(jsonObj[i][Object.keys(jsonObj[i])[j]])[k]] = jsonObj[i][Object.keys(jsonObj[i])[j]][Object.keys(jsonObj[i][Object.keys(jsonObj[i])[j]])[k]];
}
}
}
console.log([flatJSON(newObj)]);
function flatJSON(obj) {
if(typeof obj != 'object') {
return;
}
for (var l in Object.keys(obj)) {
if (typeof obj[Object.keys(obj)[l]] == 'object') {
for (var m in Object.keys(obj[Object.keys(obj)[l]])) {
newObj[Object.keys(obj)[l]+'-'+Object.keys(obj[Object.keys(obj)[l]])[m]] = obj[Object.keys(obj)[l]][Object.keys(obj[Object.keys(obj)[l]])[m]];
}
}
if (typeof obj[Object.keys(obj)[l]] == 'object') {
delete obj[Object.keys(obj)[l]];
}
if (obj[Object.keys(obj)[l]] === undefined) {
delete obj[Object.keys(obj)[l]];
}
}
return newObj;
}

Expected an identifier and instead saw '<'

I get this error at the very beginning. Not sure how to fix. I also get the expected an assignment or function call and instead saw an expression. Not to mention Expected an identifier and instead saw "var"
<script>
var interactiveSearch = {};
(function() {
interactiveSearch.common = {
init: function() {
interactiveSearch.common.setupDataTableDefaults();
$.ajaxSetup({
cache: false
});
},
setupDataTableDefaults: function() {
$.extend($.fn.dataTable.defaults, {
"sDom": "<'table-header-controls'<'row'<l><f>>r><i>t<'table-footer-controls'<'row'<'span12'p><'span12'i>>>",
"sPaginationType": "bootstrap",
"bJQueryUI": false,
"bProcessing": false,
"bServerSide": true,
"fnServerData": interactiveSearch.common.getTableData
});
},
getTableData: function(sSource, aoData, fnCallback) {
var data = new Array();
var columnCount = _.find(aoData, function(o) {
return o.name == 'iColumns';
}).value;
var echo = _.find(aoData, function(o) {
return o.name == 'sEcho';
}).value;
var skip = _.find(aoData, function(o) {
return o.name == 'iDisplayStart';
}).value;
var take = _.find(aoData, function(o) {
return o.name == 'iDisplayLength';
}).value;
var search = _.find(aoData, function(o) {
return o.name == 'sSearch';
}).value;
var sortCols = _.filter(aoData, function(o) {
return o.name.indexOf('iSortCol_') == 0;
});
var sortDirs = _.filter(aoData, function(o) {
return o.name.indexOf('sSortDir_') == 0;
});
var searches = _.filter(aoData, function(o) {
return o.name.indexOf('sSearch_') == 0;
});
data.push({
"name": "TableEcho",
"value": echo
});
data.push({
"name": "Skip",
"value": skip
});
data.push({
"name": "Take",
"value": take
});
data.push({
"name": "AllSearch",
"value": search
});
var actual = 0;
_.each(sortCols, function(columnSort, sortIndex) {
var columnIndex = columnSort.value;
var columnSearch = searches[columnIndex].value;
var sortDir = sortDirs[sortIndex].value;
data.push({
"name": "Columns[" + actual + "].ColumnIndex",
"value": columnIndex
});
data.push({
"name": "Columns[" + actual + "].SortDirection",
"value": sortDir
});
if (columnSearch != '') {
data.push({
"name": "Columns[" + actual + "].SearchTerm",
"value": columnSearch
});
}
actual++;
});
for (var i = 0; i < columnCount; i++) {
var searchTerm = searches[i].value;
if (searchTerm == '') {
continue;
}
data.push({
"name": "Columns[" + actual + "].ColumnIndex",
"value": i
});
data.push({
"name": "Columns[" + actual + "].SearchTerm",
"value": searchTerm
});
actual++;
}
$.post(sSource, data)
.success(fnCallback);
}
};
})();
$(function() {
interactiveSearch.common.init();
});
(function() {
var product = interactiveSearch.product = {};
product.init = function() {
product.initDataTable();
product.bindEvents();
};
function convertFullRowToDataObject(fullRow) {
return {
Id: fullRow[0],
ProductName: fullRow[1],
Synonym: fullRow[2],
Acronym: fullRow[3],
CasNo: fullRow[4],
EinecsNo: fullRow[5],
Formula: fullRow[6],
MolecularWeight: fullRow[7],
Status: fullRow[8],
MeltingPoint: fullRow[9],
BoilingPoint: fullRow[10],
HasDoc: fullRow[11] !== '',
RelatedDocPath: product.baseUrl + fullRow[11],
HasDImage: fullRow[12] !== '',
ImagePath: product.baseUrl + fullRow[12]
};
}
product.initDataTable = function() {
product.productTable = $("#product-table").dataTable({
aaSorting: [
[1, "asc"]
],
iDisplayLength: 15,
bServerSide: true,
bDestroy: true,
sAjaxSource: interactiveSearch.product.listUrl,
fnRowCallback: function(nRow, aData) {
$(nRow).data('rowInfo', convertFullRowToDataObject(aData));
},
aoColumns: [{
sType: "string",
sClass: "dtAlignLeft",
mData: 1
}]
});
};
product.bindEvents = function() {
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\[([\s\S]+?)\]\}/g
};
var templateText = $('#productDetailTemplate').html(),
compiledTemplate = _.template(templateText);
$(document).on('click', '#product-table tr', function(e) {
var el = $(this);
var rowData = el.data('rowInfo');
var html = compiledTemplate(rowData);
$('#productDetailContainer').empty().html(html);
$('#product-table tr').removeClass('active');
el.addClass('active');
});
$('#searchClone').on('keyup', function(e) {
var el = $(this);
var mimicEl = $('#product-table_filter input');
mimicEl.val(el.val()).trigger('keyup');
})
$('.btn-reset-filter').on('click', function() {
$('#searchClone').val('').trigger('keyup');
});
};
})();
$(document).ready(function() {
interactiveSearch.product.listUrl = '/pa/Product/ListItems';
interactiveSearch.product.baseUrl = '/pa/';
interactiveSearch.product.init();
});
</script>
In .js files you don't have to put <script>, you can just write your code.
<script> is for HTML files when you have to insert a script in the middle of the page.
So you have to delete <script> and </script> in your file.

How to add attributes to JSON array using javascripts?

I want to construct following JSON dynamically using Javascript.
{
"Events": [{
"Name": "Code Change",
"Enabled": "true",
"Properties": [{
"Name": "url",
"Value": "val"
}]
}],
"Properties": [{
"Name": "url",
"Value": "val"
}]
}
So i wrote following code but it creates JSON object where Name, Enabled and properties under separate curly brackets. Is there anyway to resolve this issue instead of using push method?
Code
var eventProperties="[{'Name':'url','Value':'val'}]";
var subscriptionProperties="[{'Name':'url','Value':'val'}]";
var eventArray = JSON.parse('[1, 5, "false"]');
var subArray = JSON.parse('[1, 5, "false"]');
var subscription = {
Events: [],
Properties: []
};
if(eventName != null && eventName != "") {
subscription.Events.push({
"Name" : eventName
});
}
var index = 0;
if(eventEnabled != null && eventEnabled != "") {
subscription.Events.push({
Enabled: eventEnabled
});
}
if(eventProperties != null && eventProperties != "") {
subscription.Events.push({
"Properties": eval('(' + eventProperties + ')')
});
}
if(subscriptionProperties != null && subscriptionProperties != "") {
subscription.Properties = eval('(' + subscriptionProperties + ')');
}
Output given
{
"Events": [{
"Name": "Code Change"
},
{
"Enabled": "true"
},
{
"Properties": [{
"Name": "url",
"Value": "val"
}]
}],
"Properties": [{
"Name": "url",
"Value": "val"
}]
}
Yes there is. You need to create only one object like so.
subscription.Events.push({
Name: eventName,
Enabled: eventEnabled,
Properties: JSON.parse(eventProperties)
});
Or using the current flow you have:
var subscription = {};
var eventObject = {};
if(eventName != null && eventName != "") {
eventObject.Name = eventName;
}
if(eventEnabled != null && eventEnabled != "") {
eventObject.Enabled = eventEnabled;
}
if(eventProperties != null && eventProperties != "") {
eventObject.Properties = JSON.parse(eventProperties);
}
subscription.Events = [eventObject];
if(subscriptionProperties != null && subscriptionProperties != "") {
subscription.Properties = JSON.parse(subscriptionProperties);
}

Find object by id in Javascript

I have this tree:
{
"id": 0,
"parentId": null,
"name": "Comapny",
"children": [
{
"id": 1235,
"parentId": 0,
"name": "Experiences",
"children": [
{
"id": 3333,
"parentId": 154,
"name": "Lifestyle",
"children": [],
"merchants": [
{
"id": 348,
"name": "Experience Mad"
},
{
"id": 30,
"name": "Virgin Experience Days"
}
]
},
{
"id": 319291392,
"parentId": 318767104,
"name": "Other Experiences",
"children": [],
"merchants": [
{
"id": 353,
"name": "Tasterlab"
},
{
"id": 19,
"name": "Activity Superstore"
}
]
}
],
"merchants": [
{
"id": 35715,
"name": "Red Letter Days"
},
{
"id": 85,
"name": "The Hut"
}
]
}
]
}
I need to find object by id. For example if need to find an object with id:353, I have to get:
{"id": 353,"name": "Tasterlab"}
if I need to find an object with id:1235, I have to get: {"id": 1235,"name": "Experiences"}
I tried many times but given the complexity of the tree for me is hard to do what I want.
function findId(obj, id) {
if (obj.id == id) {
return obj;
}
if (obj.children) {
for (var i = 0; i < obj.children.length; i++) {
var found = findId(obj.children[i], id);
if (found) {
return found;
}
}
}
if (obj.merchants) {
for (i = 0; i < obj.merchants.length; i++) {
found = findId(obj.merchants[i], id);
if (found) {
return found;
}
}
}
return false;
}
Code is taken from: http://techslides.com/how-to-parse-and-search-json-in-javascript/
Return an array of objects according to key, value, or key and value matching
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(obj);
}
}
}
return objects;
}
Return an array of values that match on a certain key
function getValues(obj, key) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getValues(obj[i], key));
} else if (i == key) {
objects.push(obj[i]);
}
}
return objects;
}
Return an array of keys that match on a certain value
function getKeys(obj, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getKeys(obj[i], val));
} else if (obj[i] == val) {
objects.push(i);
}
}
return objects;
}

Categories