I am trying to make a messenger bot that can create buttons based on a number I enter. The code looks like this:
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": text[1],
"buttons":[]
}
}
}
The part that says "buttons":[] is where I want to add buttons (inside the []) according to this format:
{
"type":"postback",
"title":"button" + i //where i is the button number,
"payload":"button" + i
}
How would I go about doing this?
For your example you can do this:
messageData.attachment.payload.buttons.push(obj)
the . accesses the object's key, which can also be done this way messageData['attachment']
The difference between
messageData.attachment
and
messageData['attachment']
is that the second one can take a variable instead of a string, e.g.
var use_key = 'attachment';
messageData[use_key];
will access the same as the other two above.
JSON is just short for JavaScript Object Notation. And you make it exactly like your second example:
{
"type":"postback",
"title":"button" + i //where i is the button number,
"payload":"button" + i
}
You can assign it to a variable to pass it into the push, or just exactly as it is. Not much different from a string or number. Don't let all the extra information scare you.
Related
"feeMap": {
"6874597a-3b20-40ea-bfa3-08358ad19793": {
"id": "6874597a-3b20-40ea-bfa3-08358ad19793",
"name": "visnhuuuu666",
"description": "One Time fee",
"cost": 13,
"isOneTimeFee": true,
"isProrated": false,
"prorateToDay": false,
"discountable": true,
"prepayable": true
}
}
inside feemap that id is a uuid how can do like that. this "6874597a-3b20-40ea-bfa3-08358ad19793": uuid is acts like object and that uuid only act as inner id value also how can I do like that dynamically is it possible. please help me this problem
I want feemap inside object should be given dynamically that is uuid and that one acts like object and also inside that object for id value also that same object uuid will add here
you can use strings for field name sin JS and access them too like so:
let feeMap = {};
feeMap["6874597a-3b20-40ea-bfa3-08358ad19793"] = {};
feeMap["6874597a-3b20-40ea-bfa3-08358ad19793"].id = "6874597a-3b20-40ea-bfa3-08358ad19793";
feeMap["6874597a-3b20-40ea-bfa3-08358ad19793"].name = "visnhuuuu666";
//and so on....
Please refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#accessing_properties
I am trying to edit the first entry in a array before it placed in another file.
This is it:
(["\"NAMES\":\"cs.js\"},[
I want to turn it into this:
([{"NAMES":"cs.js"},[
I'm using an online regex generator, but so far I've only managed to edit to this point with /.["[\]/ and substituting with ([{:
([{"NAMES\":\"cs.js\"},[
Any help given will be appreciated.
EDIT:
Here is some of the code:
var initialCourseArray = new Array()
initialCourseArray.push(["\"NAMES\":\"cs.js\"},[
{"COURSE_ID":"ENGL 1013"},
{"COURSE_ID":"FAH1"},
{"COURSE_ID":"USHG1"},
{"COURSE_ID":"TECH 1001"},
{"COURSE_ID":"COMS 1403"},
{"COURSE_ID":"COMS 1411"},
{"COURSE_ID":"ENGL 1023"},
{"COURSE_ID":"SS1"},
{"COURSE_ID":"MATH 2914"},
The stuff after is the rest of the values in the array and they do not look like this one so I'm not worried about them.
Second EDIT:
Since there is some confusion about the code that I honestly should have placed in here first, I am using a php file to retreive course data from a test database and then encoding it into JSON, formatting it, and then using fopen and fprintf to place it inside a javascript file. The part I'm giving you is what ends up inside the javascript file.
Third EDIT:
here is the code I am using to format the array. It is very messy because my leader keeps changing the format he wants the result to be in:
$row1 = "\"NAMES\"";
$colon = ":";
$row2 = "\"".$major.".js\"";
$major_name = $row1.$colon.$row2;
//The course data is already loaded into the table. This why I am using array_unshift to place the major_name inside.
array_unshift($major_array, $major_name);
array_push($major_array, "false");
$json_string = json_encode($major_array);
$re = "/.,/";
$subst = "},\r\n";
$json_string = preg_replace($re, $subst, $json_string);
$re2 = "/\,(?=[^.]*$)/";
$subst2 = ",[";
$json_string = preg_replace($re2, $subst2, $json_string, 1);
$first_string = "var initialCourseArray = new Array()";
$second_string = "initialCourseArray.push(";
$end_bracket = "]";
$end_parentheses =")";
There are several issues:
1. Don't manipulate JSON strings
You should never manipulate a string that is the result of json_encode, because you will very likely make the JSON text invalid, which is actually happening in your case.
So using this kind of statements:
$json_string = preg_replace($re, $subst, $json_string);
is asking for trouble. Once you have a $json_string, it should be final. Anything you want to happen to the structure must happen before you call json_encode.
Even if you just want to add line breaks inside a JSON string, don't do it that way. json_code provides a "pretty print" option which will do it for you:
json_encode(...., JSON_PRETTY_PRINT);
2. JavaScript does not have associative arrays
A second problem is that in JavaScript you cannot have something like
["NAMES":"cs.js" ...]
So json_encode will never generate anything like that. If you want named keys in JavaScript (like "NAMES"), you cannot define it as an array, but should define it as an object:
{"NAMES":"cs.js" ...}
json_encode will do that for you if you provide it the corresponding PHP structure (i.e. an associative array) and let it do its job without tampering.
3. Don't add "false"
It does not seem useful to add "false" as an element to the courses array. In JavaScript you can easily check how many elements there are in an array, so there is no need to put a kind of stop-sign at the end.
Anyway, if in JavaScript you refer to an element in an array that does not exist, you get undefined, which you can verify, much like verifying for the value "false".
I would strongly suggest to leave that out.
Suggested code
The PHP code you provided in your question could be replaced with this:
// Add the names element as a separate item next to the courses array,
// which we put in the "courses" property.
$major_array = array(
"names" => $major,
"courses" => $major_array
);
// Turn into JSON text with added line breaks and indentation:
$json_string = json_encode($major_array, JSON_PRETTY_PRINT);
// Don't touch the JSON text anymore, but output it:
echo "var initialCourse = $json_string;";
The output (JavaScript) would be something like:
var initialCourse = {
"names": "cs",
"courses": [
{
"COURSE_ID": "ENGL 1013"
},
{
"COURSE_ID": "FAH1"
},
{
"COURSE_ID": "USHG1"
},
{
"COURSE_ID": "TECH 1001"
},
{
"COURSE_ID": "COMS 1403"
},
{
"COURSE_ID": "COMS 1411"
},
{
"COURSE_ID": "ENGL 1023"
},
{
"COURSE_ID": "SS1"
},
{
"COURSE_ID": "MATH 2914"
}
]
};
As I mentioned above, this is an object structure, not an array structure, because JavaScript does not allow named keys in an array notation. If in JavaScript you need to iterate over the courses in the above structure, you would address the courses property (which is an array), like this:
for (var course of initialCourse.courses) {
console.log('course id: ' + course.COURSE_ID);
}
More concise structure
I must say it is a bit of an over-kill to have objects with just one property. This structure would be more concise and efficient:
var initialCourse = {
"names": "cs",
"courses": [
"ENGL 1013",
"FAH1",
"USHG1",
"TECH 1001",
"COMS 1403",
"COMS 1411",
"ENGL 1023",
"SS1",
"MATH 2914"
]
};
In JavaScript you would iterate over these courses like this:
for (var course of initialCourse.courses) {
console.log('course id: ' + course);
}
If this interests you, you should just add this line to your PHP code, before any of the PHP code I suggested above:
$major_array = array_map(function ($course) { return $course["COURSE_ID"]; }, $major_array);
If you just want to apply it to that line,
find /"?\\"/ and replace " will do it.
So I have am trying to compare 2 objects using lodash's _.isEqual method, I have pretty straight forward function that checks like so
function findMatchingQuery(savedSearch) {
if (_.isEqual(savedSearch.data.document.query, $scope.searchResults.minify())) {
return true;
}
}
The data has changed a bit and I need to pull out a piece of data inside before I do a compare.
So the each of those objects has this format -
{
"name": "item name",
"showMore": boolean,
"filters": []
}
And what I would like to do is strip out the showMore node. I tried to add the some vars using _.remove, however it seems this does not work because remove is looking for a key and value.
var modifiedSavedSearch = _.remove(savedSearch.data.document.query, { "showMore" });
var modifiedCurrentSearch = _.remove($scope.searchResults.minify(), { "showMore" });
Is there a simple way to strip away those parts of the object before running the _.isEqual on them? Doesn't have to be lodash. Thanks!
You can delete the attribute, like:
delete savedSearch.data.document.query.showMore
You can use _.omit to remove it, or you can use _.pick to pick the rest of the attributes
Yeah, omit should do what you are looking for:
var modifiedSavedSearch = _.omit(savedSearch.data.document.query, { "showMore" });
If you want to get rid of it completely, you can do the following:
// assuming this is your variable
var myVar = {
"name": "item name",
"showMore": boolean,
"filters": []
};
// delete the unwanted property
delete myVar.showMore;
I have a casperjs script which iterates over a list of pages and extracts data.
On the other hand I have a csv file with 2 fields 'ean' 'ref' which I parse with Papa.parse. The output is an object. I am looking for a solution to query an javascript object (the output from Papa.parse) for the 'ref' field and extract the 'ean'. I thought .filter() is what i was looking for but that can only search for a predefined value in the callback function.
function cd(element) {
return element == '123';
}
var b = c.filter(cd);
The problem hear is 1. It returns an empty array and 2. even if it would work I need to change the value with every call since I want to find the ean value for any given ref.
function cd(element,ref) {
return element == ref;
}
This is the data I need to search
"data": [
{
"ean": "654321",
"ref": "123"
},
{
"ean": "1234567",
"ref": "124"
}
]
I hope I made myself more clear. Thank you in advance
I used https://lodash.com/docs#where
Does exactly what i want
var a = _.where(array,{'ref' : 'value i am looking for'});
result is an array from where I can extract the value of the ean field.
Actually I want to search an attribute's value in an json array for one of its child. Now one condition is that the attribute will not be there in all the child's of the array. This is my json array.
[{
"heading1":"heading1",
"heading2":"heading2",
"heading3":"heading3",
"heading4":"heading4",
"heading5":"heading5",
"heading6":"heading6"
},
{
"column1":65536,
"column2":"school",
"column3":"testing purpose",
"column4":"DESKTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1":98305,
"column2":"Nikhil",
"column3":"Test",
"column4":"LAPTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}]
So presently I am working with the each loop but like this
var obj = $.parseJSON(JSON.stringify(response));
$.each(obj, function () {
console.log("heading1", this['heading1']);
});
Here response comes from mserver and it is the json array
Now I want to know can I search for this attribute in the json array without using a loop in jQuery.
Based on your sample code what I understand you have is an array of objects and you want to find objects with one specific property and or value:
This will return true if the object has the property
var results= arr.filter(function(item){ return item.hasOwnProperty("column5"); });
Or you can perform additional action when you find the property:
arr.filter(function(item){
if (item.hasOwnProperty("column5")) {
return item["column5"] === 'demo 01'; //or item.column5 === 'demo 01'
}
return false;
});
This only works on IE9+ if you need this to run in older versions of IE, please follow the instructions under polyfill:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The you can check like
var obj = $.parseJSON(response);
$.each(obj, function (index,value) {
if(typeof obj[index].heading2 !== "undefined")
{
alert(obj[index].heading2);
}
when in other object of array element not find then it returns undefined. and you can check like that.
you can check in this http://jsfiddle.net/gKRCH/
It's best to use a loop. But if the format of the JSON is regular, you could regex for the value in the response string.
I'm not recommending this method, just pointing out that it exists.
var value = "heading1";
if( (new RegExp('"' + value + '"')).test(response) ){
// Found value
};
Here, we take the required value, wrap it in quotation marks and search for it in the response.
This has several issues, such as:
It might find the pattern in a property name
If the value could contain regex special characters, they'll need escaping.
If your JSON contains values with escaped quotation marks, you could get a false positive from partial matches.
That's why it depends on you knowing the format of the data.
EDIT:
You can solve issue 2 by using this condition instead of regex. But it gives you less flexibility.
response.indexOf('"' + value + '"') !== -1
Try this,
$.each(object,function(key, value){
console.log(key);
console.log(value);
});
You can use this JS lib; DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search" - with which, you can perform XPath queries on JSON structures. Like the one you have exemplified.
With XPath expressions (which is standardised query language), you can find whatever you're looking for and DefiantJS will do the heavy-lifting for you - allowing your code to be neat and clean.
Here is the fiddle of this code:
http://jsfiddle.net/hbi99/q8xst/
Here is the code:
var data = [
{
"heading1": "heading1",
"heading2": "heading2",
"heading3": "heading3",
"heading4": "heading4",
"heading5": "heading5",
"heading6": "heading6"
},
{
"column1": 65536,
"column2": "school",
"column3": "testing purpose",
"column4": "DESKTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1": 98305,
"column2": "Nikhil",
"column3": "Test",
"column4": "LAPTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}
],
res = JSON.search( data, '//*[column4="DESKTOP"]' );
console.log( res[0].column2 );
// school