I'm very new to javascript and have not had any formal education on it. I've looked at multiple sources and I can't seem to find a solution to my issue.
I am trying to create a button with a value equal to an object that is nested inside other objects. I will have a lot of other buttons on my site with the same function but should refer to different data sets.
When the button is clicked I would like the function to grab the value of the button (which should be an object) and declare a new variable equal to the object that has been passed.
I can print the data I want just fine to the log, but when I try to print the value of the variable that should now how the same data I keep getting [object Object]
(From there I will be populating a graph that will change every time a new button is clicked.)
example of my object
var Wall = {
"Option1": {},
"Option2": {},
"Option3": {
"Option1_3": {
"Option1_1_3": {
"Total Something": "100",
"Total Something Else": "20",
"Another Total": "40",
"More totals": "20",
"Total": "20",
},
"Option2_1_3": {},
"Option3_1_3": {}
},
"Option2_3": {},
},
"Option4": {},
"Option5": {}
};
creating the button and when clicked function
document.getElementById('Option1_3').innerHTML = (`<button class="button" value="${Wall.Option3.Option1_3}" onclick= "PopulateGraph(this.value)">Wall Time</button>`);
console.log(Wall.Option3.Option1_3);
function PopulateGraph(val){
console.log(val);
}
Output
This happens because when you use ${Wall.Option3.Option1_3} it is gonna have the same effect as Wall.Option3.Option1_3.toString() which is [object Object] (this is true for any objects as well as Arrays)
Your choices here are:
Either use {JSON.stringify(Wall.Option3.Option1_3)
Or if you don't wanna output plain JSON you can use Object.keys() or some other methods to break down the object before parsing it.
As #Andreas already mentioned, the content of any value attribute can only be a string. So one way of doing what you wanted would be to convert the objects into JSON-strings and convert them beack at the time of the button click:
var Wall ={
"Option1":{},
"Option2":{},
"Option3":{
"Option1_3":{
"Option1_1_3":{
"Total Something":"100",
"Total Something Else":"20",
"Another Total":"40",
"More totals":"20",
"Total":"20",
},
"Option2_1_3":{},
"Option3_1_3":{}
},
"Option2_3":{},
},
"Option4":{},
"Option5":{}};
document.getElementById('Option1_3').innerHTML = (`<button class="button" value='${JSON.stringify(Wall.Option3.Option1_3)}' onclick= "PopulateGraph(this.value)">Wall Time</button>`);
// console.log(Wall.Option3.Option1_3);
function PopulateGraph(val){
console.log(JSON.parse(val));
}
<div id="Option1_3"></div>
Alternatively you could not assign the actual object to the button but only the key to finding the object (as a string: "Wall.Option3.Option1_3"). The button click handler will then find the object on the basis of the passed key:
var Wall ={
"Option1":{},
"Option2":{},
"Option3":{
"Option1_3":{
"Option1_1_3":{
"Total Something":"100",
"Total Something Else":"20",
"Another Total":"40",
"More totals":"20",
"Total":"20",
},
"Option2_1_3":{},
"Option3_1_3":{}
},
"Option2_3":{},
},
"Option4":{},
"Option5":{}};
document.getElementById('Option1_3').innerHTML = (`<button class="button"
value="Wall.Option3.Option1_3" onclick= "PopulateGraph(this.value)">Wall Time</button>`);
function PopulateGraph(addr){
console.log(addr.split('.').reduce((a,c)=>a[c],window));
}
<div id="Option1_3"></div>
The expression addr.split('.').reduce((a,c)=>a[c],window) deserves some further explanation: The "address string" addris first split into its components: ['Wall','Option3','Option1_3'] and then the reduce() method is applied. The reduce callback function takes each value in turn and returns an underlying object of the passed a object. Initially a is set to the window object, where the Wall variable can be found as a property. The found sub-object is returned and will be used as a in the next reduce-iteration.
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'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
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 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.
I have below function in my dojo class:
dojo.declare("someclass", null, {
getSomeObject: function(id, name, description) {
console.log("id=", id, ", name=", name, ", description=", description);
var newObj = {
"id": id,
"name": name,
"description": description
};
console.log("newObj=", newObj);
return newObj;
}
});
This was fine until I upgraded the product I was working on. When I run the code now, somehow inside "newObj", all attribute values are turned into array - i.e. when "123" is passed as id value to function, inside newObj, "id" attribute value is ["123"].
I have tried using different ways to create object - with "new Object()", etc. Nothing seems to help. When I run the same code in the old product, it works as expected!!!
Here is an output from Google Chrome console --
id= 5962960 , name= sng2 , description= test
newObj=
Object
_RI: true
description: Array[1]
id: Array[1]
name: Array[1]
__proto__: Object
Any help???
I suppose you are using an ItemFileReadStore or ItemFileWriteStore.
Then it is absolutely normal, these stores works with arrays internally.
To get the value you should do as recommended in the doc:
store.getValue(storeItem, "property");
or if you're certain that value represented in propery, you can safely typecast by doing + ""