Pass an array of objects to another function onclick - javascript

I just want to ask how to pass an array of objects to another function.
I have a function
function btnB(weekly) {
console.log(weekly);
}
function btnA() {
const array = [{ abc : 123 }, { def : 456 }]
div.innerHTML = `<div onclick="btnB(${array[0]});"`;
divList.appendChild(div);
}
btnA();
And I'm getting an error
Uncaught SyntaxError: Unexpected identifier

You can't substitute an object like that in a template literal. It converts the object to a string, which returns [Object object].
Use JSON.stringify() to convert it to an object literal.
function btnA() {
const array = [{ abc : 123 }, { def : 456 }]
div.innerHTML = `<div onclick='btnB(${JSON.stringify(array[0])});'`;
divList.appendChild(div);
}
You also should use single quotes around the onclick value, because JSON uses double quotes around the object keys.

function btnB(weekly) {
console.log(weekly);
}
function btnA() {
const array = [{ abc : 123 }, { def : 456 }];
const div = document.createElement('div'); // delete if useless
div.addEventListener('click', () => {
btnB(array[0])
});
divList.appendChild(div);
}

I'm assuming the [0] is part of your attempt to solve this, but based on the question asking to pass an array of objects to the click handler, I'll refer to that instead.
Inline event handlers are deprecated and problematic anyway, but using them in HTML generated by JavaScript completes the circle in an absurd way. It would be a lot easier and more robust (and secure) to attach the click handler via JavaScript as well, as follows:
const array = [{ abc: 123 }, { def: 456 }]
div.innerHTML = '<div></div>' // Just the inner div without onclick
div.firstElementChild.addEventListener('click', () => btnB(array))
divList.appendChild(div)

Related

Callback from Peggy generated parser

I want to parse a string that is generated inside a class instance by calling a peggy generated parser. One of the parsing actions needs to invoke a function defined inside the class instance, so that I have access to the environment of that instance, including this. How can I make that happen?
You can set a "global-initializer" at the start of your grammar. You should be able to set up your environment there. From the docs:
const parser = peggy.generate(`
{
// options are available in the per-parse initializer
console.log(options.validWords); // outputs "[ 'boo', 'baz', 'boop' ]"
}
validWord = #word:$[a-z]+ &{ return options.validWords.includes(word) }
`);
const result = parser.parse("boo", {
validWords: [ "boo", "baz", "boop" ]
});
console.log(result); // outputs "boo"

Is there a way to call the map method only if the element is an array?

I am using the query-string library to parse query parameters from an URL.
When the query parmater is in the form ?foo=bar, the lib returns an object like this:
{
foo: bar
}
When in the form ?foo=bar1,bar2, the object looks like this:
{
foo: [bar1, bar2]
}
I want to apply the function myFunction on each element of myObject.foo to obtain something like [myFunction(bar)] or [myFunction(bar1), myFunction(bar2)]
Is there a way to do it easily with something like
myObject.foo.mapOrApply(myFunction)
without having to check if this is an array ?
For now, I am forced to do it this way and I find this very unaesthetic:
Array.isArray(myObject.foo)
? myObject.foo.map(myFunction)
: [myFunction(myObject.foo)];
You could use concat like this:
[].concat(myObject.foo).map(myFunction)
This works when myObject.foo is a single value or an array
Here's a snippet:
const getMapped = ({ foo }, callback) => [].concat(foo).map(callback);
// double a single value
console.log(getMapped({ foo: 1 }, n => 2 * n))
// prefix "new" to every item in the array
console.log(getMapped({ foo: ["bar1", "bar2"] }, str => "new " + str))
You could convert to an array, if neccessary, then map with the function.
result = (Array.isArray(myObject.foo) ? myObject.foo : [myObject.foo]).map(myFunction);
You can simply :
[].concat(myObject.foo).map(myFunction)

JavaScript request object- convert key as a variable to string

I'm a programming beginner.
API post call accepts object variable (derived from variable) as a string as follows
"option":
{
"235": “30”
},
{
"238": “32”
}
My code angular 6
option = [];
---
this.option.push({
[option.product_option_id]: $event
});
which result
option = [ {
235: 30
}]
but need this variable in double-quoted "235".
please help
but need this variable in double-quoted "235"
By which you mean that you need it to be a string.
Don't worry, it is. When you use a number as a property name, it's converted to a string automatically. Property names can only be strings or Symbols, so things that aren't strings or Symbols get converted to string:
class Example {
constructor() {
this.option = [];
const option = {
product_option_id: 42
};
const $event = {};
this.option.push({
[option.product_option_id]: $event
});
const pushed = this.option[0];
for (const key of Object.keys(pushed)) {
console.log(`${key}: ${typeof key}`);
}
}
}
new Example();
That said, the expression within the [] of a computed property name is just that: an expression. So if you wanted to be explicit, you could use String there:
option.push({
[String(option.product_option_id)]: $event
});

Create object from object literal string

Is there an easy way to parse an object literal as a string into a new object?
I'm looking to turn a string like the following:
'{ name: "A", list: [] }'
Into an object like:
{ name: 'A', list: [] }
Note:
I'm not looking for JSON.parse() as it accepts json strings and not object literal strings. I was hoping that eval would work but unfortunately it does not.
eval does indeed work, with one tweak: the problem is that the standalone line
{ name: 'A', list: [] }
gets parsed as the interpreter as the beginning of a block, rather than as the start of an object literal. So, just like arrow functions which implicitly return objects need to have parentheses surrounding the objects:
arr.map(item => ({ item }))
you need to put parentheses around the input string, so that the content inside (that is, the object, which starts with {) is parsed properly as an expression:
const input = '{ name: "A", list: [] }';
const obj = eval('(' + input + ')');
console.log(obj);
Of course, as with all cases when eval is involved, you should be very sure that the input is trustworthy first.
While I would never do this IRL, you could perhaps try this:
var myObjLiteralString = '{ name: "A", list: [] }';
var myObj;
eval('myObj = ' + myObjLiteralString);
console.log(myObj);

Access a predefined child object from its parent object with a string

I have a javascript object that has been returned from a Database.
I want to build a function that, if passed a parent object and a string, can return a child from the parent with the same name as the string.
the following code obviously does not work, but gives the idea:
function filter (object, text) {
return object.Text
}
such that
var object = {
"prop1": 1,
"prop2":
{
"ChildProp1": 1,
"ChildProp2": 2,
}
}
var text = "prop2"
var ChildObject = filter(object, text)
//expected content of ChildObject = {
// "ChildProp1": 1,
// "ChildProp2": 2,
// }
You don’t need a function to access a property by name; it’s a fundamental part of JavaScript’s syntax.
object[text]
Try using this:
function filter(object, text) {
return object[text];
}
This allows you to dynamically access a property with bracket notation, instead of statically accessing one with dot notation.
Just use array syntax,
Object["property"]

Categories