Getting "SyntaxError: Unexpected token" in Observable - javascript

I was trying vega-lite-api on observablehq here.
This is my code:
Putting these two in different cells work:
obj = vl.markPoint()
.data(df)
.encode(vl.y().fieldN('city'));
In next cell:
obj.render()
If I put both in the same cell, it gives SyntaxError: Unexpected token:
obj2 = vl.markPoint()
.data(df)
.encode(vl.y().fieldN('city'));
obj2.render();
^
Why is this so?

If you want to put the code into the same cell, you can either chain the call to render like so:
vl.markPoint()
.data(df)
.encode(vl.y().fieldN('city'))
.render()
Or you can use a block cell with curly braces like so:
{
const obj = vl.markPoint()
.data(df)
.encode(vl.y().fieldN('city'));
return obj.render();
}
For more on Observable JavaScript:
https://observablehq.com/#observablehq/observables-not-javascript

for obj you have a definition before you use it...
obj = N {
Symbol(data): Object {mark: h, data: Object, encoding: h}
<prototype>: N {}
}
I guess you forgot about it for obj2?

Related

How do I set a JavaScript object's value to null

I have created this JS object from an array.
var rv = {};
$( ".part-name:visible" ).each(function( index ) {
//rv[$(this).text()] = arrayPartsName[$(this).text()];
rv[$(this).text()] = arrayPartsName[$(this).text()];
console.log(rv);
})
4GN: "4GN"
4GNTS: "4GNTS"
042645-00: "042645-00"
503711-03: "503711-03"
573699-05: "573699-05"
I have to use this object with Materialize Autocomplete and I have to edit it. The correct object must be, for example, like this
4GN: null
4GNTS: null
042645-00: null
503711-03: null
573699-05: null
How can do this?
Picking up from my comment. You can just set it to null ;) JavaScript is quite a cool language... you can pretty much set any object's properties to anything you want, null, a specific value, or even a function... see some more on the topic
But to focus on your specific question:
Change this line
rv[$(this).text()] = arrayPartsName[$(this).text()];
to
rv[$(this).text()] = null;
Something to be aware of
If you have property or key values in the JSON object with a dash in the name, you have to wrap it in quotes ", otherwise it wont be seen as valid. Although this might not be as evident, or an issue in your example as your keys are being added via the following function $(this).text().
var fruit = {
"pear": null, // something null
"talk": function() { console.log('WOOHOO!'); } // function
}
var apple = "app-le";
fruit[apple.toString()] = 'with a dash';
fruit["bana-na"] = 'with a dash';
// below is not allowed, the values will be evaluated as
// properties that dont exist, and then your js will fail
// fruit[pe-ar] = 'with a dash';
fruit.talk();
console.log(fruit);

Transform array into newline separated string using map.reduce?

I think it should be possible to use map.reduce to transform an array into newline separated string. But for some reason it is not working. What am I doing wrong
copyLicenseCodesToClipboard = () => {
// tslint:disable-next-line:no-any
const licenseCodes = this.props.generateLicenseCodes.reduce((accumulator: any, element: LicenseCode) =>
accumulator.concat(element.code).concat('\n')
);
copyToClipboard(JSON.stringify(licenseCodes));
}
Uncaught TypeError: accumulator.concat is not a function
You can also use map and join, which seems to be more intuitive in this case.
const licenseCodes = this.props.generateLicenseCodes.map((element)=>{return element.code;}).join("\n");

Cannot Read Property 'Push' of undefined - Typescript

When I try to add to an array in Typescript (wrapped in Ionic2) I get an error telling me the array is undefined even though I've declared it. I've tried declaring it using two different declarations and not found the problem. The two declarations I used are:
tracker: any[];
and
tracker: Array<any>;
The first time I try to add anything to the array and where I get the error is below. I wanted to include the whole function, just in case there was something in there that could be redefining what 'this' is:
// Answer Correctly
answerQuestionCorrectly(answer) {
let answerButton = <HTMLButtonElement>document.getElementById('answer-' + answer.AnswerId);
answerButton.addEventListener('click', (event) => {
// Increase the score
this.currentScore = this.currentScore + this.countdown;
// Set up quiz review
var correct = answer.AnswerText;
var qTrack = {no: this.questionNo, q: this.questionText, a: answer.AnswerText, c: correct}
console.log(qTrack);
this.tracker.push(qTrack);
console.log(this.tracker);
// Check for end of questions
if (this.questionNo < this.noOfQuestions) {
// Remove the old answers
var parent = document.getElementById('answers');
this.answers.forEach(element => {
var button = <HTMLButtonElement>document.getElementById('answer-' + element.AnswerId);
parent.removeChild(button);
});
// Re-init the timer
this.timer.initTimer();
// Load Next Question
this.loadQuestion();
} else {
// End the Quiz
this.endOfQuiz();
}
});
}
Those declarations only specify the type of the variable — it also needs a value. Try something like
var tracker: any[] = [];
to initialise the variable to an empty array.
You have to initialize the array before you can push an object into it.
tracker: any[ ] = [ ];
You must initialize it like this:
tracker: Array<any>=[];

jsx unexpected token passing array of object

<SettingsDropdown labelName="Settings" items={[
{name:'Feature Listing', handler:{this.handle_dropdown_featureListing}, divider:true}
]}/>
What's wrong with my above syntax?
I do have
handle_dropdown_featureListing = () => { //something } but I got unexpected token error still.
handler:{this.handle_dropdown_featureListing}
here you have an object literal that does not have a key.
It must be
handler:{keyName: this.handle_dropdown_featureListing}
or whatever name you need.
Or if you need to pass a single function reference - just remove the curly braces:
handler: this.handle_dropdown_featureListing

Estrange behaviour in JavaScript array clone equality assertion

I have found a failing assertion in a JavaScript unit test that I would like to fix. The unit test code is the following (the full code can be found here):
beforeEach(function() {
arrNeedle = ['waffles'];
objNeedle = {w: 'waffles'};
strNeedle = 'waffles';
numNeedle = 3.14159
arrDupe = JSON.parse(JSON.stringify(arrNeedle));
objDupe = JSON.parse(JSON.stringify(objNeedle));
strDupe = JSON.parse(JSON.stringify(strNeedle));
numDupe = JSON.parse(JSON.stringify(numNeedle));
arrContainer = [arrDupe, objDupe, strDupe, numDupe];
objContainer = {
arr: arrDupe
, obj: objDupe
, str: strDupe
, num: numDupe
};
arrMissing = ['chan'];
objMissing = {missing: 'chan'}
strMissing = 'chan';
});
it("has its test set up correctly", function() {
arrNeedle.should.not.equal(arrDupe);
objNeedle.should.not.equal(objDupe);
arrContainer.should.not.contain(arrNeedle);
arrContainer.should.not.contain(objNeedle); // fails
objContainer.arr.should.not.equal(arrNeedle);
objContainer.obj.should.not.equal(objNeedle);
});
In the test we are cloning an object and inserting it into an array:
objNeedle = {w: 'waffles'}; // original
objDupe = JSON.parse(JSON.stringify(objNeedle)); // clone
arrContainer = [arrDupe, objDupe, strDupe, numDupe]; // add clone to array
The failing assertion checks that the array (contains the cloned object) doesn't contain the original object.
arrContainer.should.not.contain(objNeedle); // fails
I tried with an external assertion plugging (chai-things) with no luck:
arrContainer.should.not.include(objNeedle); // fails
arrContainer.should.not.include.something.that.deep.equals(objNeedle); // fails
The following assertion pass the test but is not the ideal solution:
arrContainer[0].should.not.equal(objNeedle); // pass
Do you know why is the array considered equal to it's clone only in some cases?
Thanks in advance :)
If you take a look at the ChaiJS code, you will see on line 189 of /lib/chai/core/assertions.js the following:
if (_.type(obj) === 'array' && _.type(val) === 'object') {
for (var i in obj) {
if (_.eql(obj[i], val)) {
expected = true;
break;
}
}
}
This is inside the include(val, msg) function, which is what is used by the .contains() matcher (see line 215).
This means that if the obj (the thing being tested) is an array and the val (the parameter to the .contains() matcher function) is an object, as it is in your case, it will check for deep equality using _.eql() (_.eql is an alias for the function provided/exported by the external deep-eql module).

Categories

Resources