I'm trying to append results in an object as options in a datalist dropdown, and it works but the problem is not all elements have a certain level in the object always which affects what results get appended to the list.
$("#returnedProducts").append($("<option/>",
{
"srindex": i,
"data-details": JSON.stringify(result[i]._source.name.family),
//I want to say if result[i]._source.fabric exists, then do this next line else, just move to "value"
"data-fabric":JSON.stringify(result[i]._source.fabric[1]),
"value": result[i]._source.category,
"html": result[i]._source.category,
}
));
How can I make this say "Only set data-fabric if result[i]._source.fabric exists,else don't set it and move to "value"?
Use a ternary operator:
{
"srindex": i,
"data-details": JSON.stringify(result[i]._source.name.family),
"data-fabric": result[i]._source.fabric ? JSON.stringify(result[i]._source.fabric[1]) : undefined,
"value": result[i]._source.category,
"html": result[i]._source.category,
}
Let me know if this needs more clarification
You really can't do something like that inside an object initializer, but you can easily do it if you assemble your options object in a function:
$("#returnedProducts").append($("<option/>", function() {
var object = {
"srindex": i,
"data-details": JSON.stringify(result[i]._source.name.family),
"value": result[i]._source.category,
"html": result[i]._source.category,
};
if (result[i]._source.fabric) {
object["data-fabric"] = JSON.stringify(result[i]._source.fabric[1]);
}
return object;
)() ); // note that the function is called here
Related
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.
I have a JSON object which looks like this:
var JSON = {
"implants":[{
"familyId": "3",
"reference": "1234",
"quantity": "3"
},{
"familyId": "2",
"reference": "3456",
"quantity": "1"
}]
}
I'm building a function which searches whether an implant with the given "reference" is already in the array. If it's not, it just gets added to the array. Easy. If it is in the array, then I want to add the new quantity to the existing quantity and then update the array.
function returnTheseImplantsWhere(key1,key2){
return function(el){
if(el[key1]==key2) {
return el;
}
}
}
var activeCaseImplants = JSON.parse(getLocal("activeCaseImplants"));
var existingImplant = activeCaseImplants.implants.filter(returnTheseImplantsWhere("reference", window.currentImplantRef));
if(existingImplant.length) {
//previously added implant
newImplantQty = Number(existingImplant[0].quantity) + Number($("#qty").val());
existingImplant.quantity = newImplantQty;
} else {
//new implant
}
My question relates to the "previously added implant" section of the above code (which all works as expected). I now have the updated quantity, but I can I determine which object within the activeCaseImplants.implants array needs it's quantity updated? I feel like I could make use of indexOf somewhere around the line beginning with var existingImplant = ... but I'm not sure where or how. Any ideas?
I am creating objects when textbox having some values (using ng-blur and textbox.value!==undefined) and then putting these objects in an array (all working fine here).
When I click on checkbox (checkbox model bind with textbox ng-required) I need to delete that particular object having that textbox value.
I am using:
arr.splice(index,1);
to remove that particular object from array (by matching it's name like "monthly" or "quarterly" etc.), but it is creating null at that particular position.
for e.g. [object,object,object]
[
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
]
after removing all element it shows [] and when I add another new object it displays [3:object] and it's content as [null,null,null,object];
or
if I remove middle object say name:"quarterly", it shows [object,object] but after adding a new object it display array as [object,object,null,object] with length of array as 4.
Why is there null and how can I remove that from array. (don't want to iterate again to check null).
It is difficult to say why your code creates the null values without have a look to it.
But I can say you that it is not the expected behaviour.
You can see this example to get some inspiration:
var data = [
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
];
var newObjectToBeAdded = { name: "daily", amount:"100" }
function showObjects()
{
document.body.innerHTML += data + '<hr>';
}
function deleteObjectByName( objectName )
{
for( var i = 0; i < data.length; i++ )
{
if( data[ i ].name == objectName )
{
data.splice(i, 1);
}
}
}
function addObjectToData( newObject )
{
data.push( newObject );
}
showObjects();
deleteObjectByName( "quarterly" );
showObjects();
addObjectToData( newObjectToBeAdded );
showObjects();
Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:
var new_array = original_array.splice( index );
Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.
Hope it helps!
var arrayWithoutNulls = myArray.filter(function(val) {
if (val) {
return val;
}
});
I have a JSON Object, that i need to loop through and delete some elements. However after I delete an element I end up with an undefined element instead, this is causing me issues, as I am unable to use this "new JSON" (I am trying to use it within datatables)
the following is what I am currently doing
function dTable(presId){
var allregos = '[{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"},{"presId": "a09N0000004UbBnIAK","name": "test catty","id": "001N000000O98IoIAJ"},{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"}]';
var newJson;
var regoValue;
for (var ke in allregos) {
if (allregos.hasOwnProperty(ke)) {
regoValue = allregos[ke].presId;
if(regoValue != presId){
delete allregos[ke];
}else{
//INstead of delete I could maybe create a new JSON by adding the whole node?
//but I am unable to add the node
//newJson = newJson.allregos[ke];
}
}
}
console.log(allregos);
console.log(newJson);
j$('#myRegos').dataTable( {
"data": newJson,
"destroy": true,
"columns": [
{ "title":"Name", "mData": "name", "class": "center" },
]
} );
}
my console log shows me something like:
[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, Object { presId="a09N0000004W3YLIA0", name="name 1", id="001N000000Mw7knIAB"}, Object { presId="a09N0000004W3YLIA0", name="Call Centre", id="001N000000MvDaMIAV"}, Object { presId="a09N0000004W3YLIA0", name="Who Is", id="001N000000MvIiaIAF"}]
is there a way to get rid of the undefiend elements?
The other work around that I was thinking was instead of deleting the elements add the appropiate ones into a new JSON however I am not able to do this. I was trying something like:
newJson = newJson.allregos[ke];
Here we have allRegos as an array of objects so a better way to use it is to take advantage of the standard for without using for (var ke in allregos) and then
if (allregos.hasOwnProperty(ke))
and also i'm converting the json string to a real json data by calling JSON.parse(allregos)
below is the enhanced dTable function
note also that i added another object with presId='a09N0000004UbBnIAz' just to see if we are getting the right answer when we call the dTable('a09N0000004UbBnIAK');
function dTable(presId){
allregos = '[{"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"}, {"presId": "a09N0000004UbBnIAK","name": "test catty","id": "001N000000O98IoIAJ"}, {"presId": "a09N0000004UbBnIAK","name": "Something","id": "001N000000Mw7knIAB"},{"presId": "a09N0000004UbBnIAz","name": "Something","id": "001N000000Mw7knIAB"}]';
oldJson = allregos;
var regoValue;
allregos = JSON.parse(allregos);
oldJson = JSON.parse(oldJson);
newJson = [];
for( i=0;i<allregos.length;i++){
regoValue = allregos[i].presId;
if(regoValue != presId){
delete allregos[i];
}else{
newJson.push(allregos[i]);
}
}
console.log('allregos before:');
console.log(oldJson);
console.log('allregos after:')
console.log(allregos);
console.log('newJson after:')
console.log(newJson);
}
You can get rid of the elements by completely overwriting the object.
Say you have
var myObject = {
"keyFoo" : "valueFoo",
"keyBar" : "valueBar",
"keyBaz" : undefined
};
in order to find out which values are not undefined, you can gothrough your object, and only set values which return true. In this scenario, you can isolate "keyBaz", because
(x.keyBaz) returns false when coerced into a boolean context, whereas
(x.keyFoo) and (x.KeyBar) both return true when coerced into a boolean context. You can do also do this within an array.
You can then overwrite the object by doing:
myObject = {
"keyFoo" : "valueFoo",
"keyBar" : "valueBar"
};
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.