adding an object to an empty <a/> in jQuery - javascript

I'm attempting
var a = $("<a/>");
then I'm trying to fill this empty variable with the contents of an object, set to variable 'obj'
obj = {
Name: " Ben",
number: 666,
}
I have tried to append a using the various methods
a.append(obj);
a.append("("+obj+")");
but if I then do:
console.log(a)
there is no way to tell if the object is now in the link tag. If I look in the console on the site I can see
([object Object])
rather than the contents. Am I missing something?

By just appending the object it is implicitly coerced to a string, hence you see [Object object].
You need to convert the object to a legible string manually. You can do that by using JSON.stringify(), like this:
var $a = $('<a href="#"/>').appendTo('body');
var obj = {
Name: " Ben",
number: 666
};
$a.text(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You have to use property of object
like below
var a = $("<a/>");
obj = {
Name: " Ben",
number: 666,
}
a.text(obj.Name + ' ' + obj.number);

Related

Pass an array of objects to another function onclick

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)

JavaScript: correct way to set object parameters with name and default value

What I'm trying to do is to pass an object to a function, where certain default values may be set, and the whole object shall have a name to pass it to another function.
The following code, without naming the parameter, works just fine.
function test({
item1,
item2 = 0
}) {
console.log(item1 + " " + item2);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}
But if I now start setting obj = {...} to pass to print() I get a syntax error:
function test(obj = {
item1,
item2 = 0
}) {
print(obj);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}
If I write item2: 0, there will be no error, but then in print item2 is undefinded.
From the answers below, this seems to be the way that works best for me so far:
function test(obj) {
obj = Object.assign({
item1: undefined,
item2: 0
}, obj);
print(obj);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}
Destructuring extracts properties from an object passed to the function and puts those properties into standalone variables - that's all. What you're trying to do is mutate one of the parameters, not extract properties from the parameter into standalone variables.
You can't mutate parameters inside a parameter list - for the sort of logic you're looking for, you'll have to do it inside the function body of test:
function test(obj) {
if (!obj.hasOwnProperty('item2')) {
obj.item2 = 0;
}
print(obj);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}
If you have lots of properties you want to assign default values to, you can use Object.assign:
function test(obj) {
const filledObj = Object.assign({
item2: 0,
item3: 'item3'
}, obj);
print(filledObj);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj);
}
If you only want an object with certain properties to pass to print, then extract those properties in the parameter list like you're doing originally, then pass a reconstructed object of only those properties to print:
function test({
item1,
item2 = 0
}) {
const obj = { item1, item2 };
print(obj);
}
test({
item1: "foo"
});
function print(obj) {
console.log(obj.item1 + " " + obj.item2);
}
= is invalid for assigning values in javascript, you are looking for {key: value}.
Change the = to : to fix the error:
// You want to destructure you object, drop the `obj =`
function test({item1,item2 = 0}) {
// If you were to modify this data,
// use `Object.assign({}, {item1,item2})` to prevent mutating your data
print({item1,item2});
}
// save some space by destructuring the items you want
function print({item1, item2}) {
console.log(`${item1} ${item2}`);
}
// Initial expected result
test({item1: "foo"});
Object Destructuring vs Default Values
I am assuming that you expect the value of item2 to equal 0 correct? It does not equal 0 because you are passing in a new object that overrides the object in your function parameters.
Just like how if you were to set:
function(a = 1){}
and pass in a value, a will no longer equal 1 because it has been replaced with a new value.
The reason you get your expected behavior in your first code snippet (without having obj = {...}) is because you are destructuring an object. This is not an assignment, rather, you are extracting pieces that you want from the object.
When you have a function with the arguments like:
function({arg1, arg2}){}
JavaScript will pull out these keys from an object you pass in.
Assigning default values
If, on the other hand, if you want to pass in an object without destructuring you may do it like so:
function(obj = {a: 'default'}){}
But, if you pass in an object in the function directly above, the default value for the object and all of its keys (a or any others) will be replaced with whatever object you pass in. Here is a link on how default parameters work in javascript.
I highly recommend you take a gander at destructuring, it is incredibly useful when dealing with objects or arrays in javascript.
Hope this helps,

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);

Reference JS object through concatenation

I am trying to call an object.
The way I am currently doing it:
var key = object_0
The way I'd like to do it
var key = "object_" + questionId;
But when calling the concatenated object_0 I do not get the object info
when I do a:
console.log(key)
Any insight would be awesome.
Short answer: global scope + brackets.
window['object_'+questionId] = 'foo';
console.log(window['object_'+questionId]); // 'foo'
Long answer: Use dynamic variable names in JavaScript
If you use ES5 you can do so with creating new empty object. Here are the steps:
1.create empty object
var o = {};
2. use brackets to produce the new key on an object - ("object_" + questionId) - this will force the parser first to evaluate expression in the brackets
3.assign value to a newly added key
o[("object_" + questionId)] = XXX;
Then console.log(o) will output {object_0: XXX}
You can use the window object (access to global variables only):
var object_0 = { p: 42 },
questionId = 0,
key = "object_" + questionId;
document.write(window[key].p);
But i suggest to change the data structure to a more concise style:
var questions = { 200: { p: 42 }},
questionId = 200;
document.write(questions[questionId].p);

Why is this javascript object code not working?

var house = new Object(floors: "4", color:"red", windows:"lots", bathrooms:"3");
var result ="";
for (var i in house)
{
result +="house." + i + " is " + house.i + ".<br />";
}
document.body.innerHTML += result;
I want to output house.floors is 4.<br />house.color is red.<br />and so on.
The Object constructor doesn't work like that. Use an object literal instead.
var house = { floors: "4", color:"red", windows:"lots", bathrooms:"3" }
Additionally house.i will reference the i property, not the property with the name that is stored in the string i, you want house[i].
Curly brackets:
var house = {floors: "4", color:"red", windows:"lots", bathrooms:"3"};
There's rarely a need (in fact I can't think of a reason) to use an explicit Object constructor call; just use {} for a new, plain, empty Object instance, and [] for a new, plain, empty Array instance. For objects with initial properties, use the "name:value" syntax like you did (except in curly brackets).

Categories