"new Set" is returning an empty set in nodejs - node.js

I was testing some websites using the below function with n, suddenly "new Set" started returning empty Array as the following:
function collectAllSameOriginAnchorsDeep(sameOrigin = true) {
const allElements = [];
// Some coding here
const filtered = allElements
// Some coding here
console.log(filtered) // The items are printed in the log probably
return Array.from(new Set(filtered)); // Nothing is getting returned!
}
If I replace the last line with return Array.from(filtered), then it works fine but I'm using "Set" to remove any repeated values.

Because Set receives iterable object as its input parameter, and will create set object respectively. Hence, we can construct a set from an array — but it will only include distinct elements from that array, aka no duplicate.
And of course, we can also convert a set back to array using Array.from() method.
let set = new Set([1,2,3]); // {1,2,3}
let arr = Array.from(set);//[1,2,3]
So you need to convert set back to array , please check here to understand the difference between set and array.
Hope this will help you!

Related

Is there a way to use variables as key in an object to find its value in rust? [duplicate]

This question already has answers here:
Access struct field by variable
(3 answers)
Closed last month.
I am new to rust with a javaScript background and i am stuck with getting a value of a json key dynamically.
In JS if i have an object = { "xyz" : "one" , "jkl" : "two" }; and if i have a variable name = "xyz"; , then i can find the corresponding value of 'xyz' key in the object using object[name] which will give me "one" as a result.
Now i have the exact same flow in rust, where i have
let obj = config.clone(); // because config is struct (only cloning could remove the error)
let name = "xyz"; // A variable which is a key in the object
let result = obj[name];` // result which is giving me "cannot index into a value of type `Configuration`" error
I am aware that creating a dict or hashmap will exponentially reduce the time, but the object i have can contain upto 1000 keys and values or more.
If i can create a hashmap with the object I already have, that would be a relief ( only if i knew ).
I have tried multiple ways by just googling a bunch of stuff
let result = obj[name];
let result = obj.&name];
let result = obj[$name];
let result = obj[&name];
let result = obj.$name;
none of them seems to solve the issue.
Thanks in advance.
Accessing fields of structs dynamically is not possible out of the box. See this earlier question.

NODE.JS: iterating over an array of objects, creating a new key if it does not exist

I am iterating over a collection of data, in my case, an array of objects. Here is a sample of 2 data points from it:
{
violation_id: '211315',
inspection_id: '268804',
violation_category: 'Garbage and Refuse',
violation_date: '2012-03-22 0:00',
violation_date_closed: '',
violation_type: 'Refuse Accumulation' },
{
violation_id: '214351',
inspection_id: '273183',
violation_category: 'Building Conditions',
violation_date: '2012-05-01 0:00',
violation_date_closed: '2012-04-17 0:00',
violation_type: 'Mold or Mildew' }
I need to create a new array of objects from this, one for each "violation_category" property. If Violation category already exists in the new array I am creating, i simply add the information to that existing category object (instead of having two "building conditions" objects for example, I would just add to an existing one).
However, I am having trouble assigning to the existing object if the current one exists (it's easy to check if it does not, but not the other way around). This is what am attempting to do currently:
if (violationCategory.uniqueCategoryName) {
violationCategory.uniqueCategoryName.violations = results[i].violation_id;
violationCategory.uniqueCategoryName.date = results[i].violation_date;
violationCategory.uniqueCategoryName.closed =
results[i].violation_date_closed;
} else {
category.violations = results[i].violation_id;
category.date = results[i].violation_date;
category.closed = results[i].violation_date_closed;
violationCategory.push(category);
}
In first condition, if this category (key) exists, I simply add to it, and in the second condition, this is where I am struggling. Any help appreciated. Thanks guys.
Just add an empty object to the key if there no object there :
violationCategory.uniqueCategoryName = violationCategory.uniqueCategoryName || {};
And only then, add the data you want to the object.
violationCategory.uniqueCategoryName.violations = results[i].violation_id;
violationCategory.uniqueCategoryName.date = results[i].violation_date;
violationCategory.uniqueCategoryName.closed =
results[i].violation_date_closed;
No condition needed.
Good luck!
Assuming that you have an input variable which is an array of objects, where the objects are looking like the objects of the question, you can generate your output like this:
var output = {};
for (var item of input) {
if (!output[item.violation_category]) output[item.violation_category] = [];
output[item.violation_category].push(item);
}
Of course you might customize it like you want.

How to reset array to empty in nodejs?

In project I define an empty array var reply= []; and in a portion of code and conditions I had o reset it to its origin as an empty array. any one can help how to do this instead of using pop method.?
some times tiny questions are looking so big.
try:
reply = [];
You have to set length of an array to zero or use splice.
reply.length = 0
// or
reply.splice(0, reply.length)
setting it to [] will create a new array.

Why does this Context.Sync not work?

Why does this code snippet not write the values back to Excel unless I un-comment the range.values=range.values line?
$('#run').click(function() {
invokeRun()
.catch(OfficeHelpers.logError);
});
function invokeRun() {
return Excel.run(function(context) {
var range = context.workbook.worksheets.getItem("Sheet1").getRange("A1:B3");
range.load('values');
return context.sync()
.then(function() {
range.values[1][1]=99;
console.log(JSON.stringify(range.values));
//range.values=range.values
return context.sync();
});
});
}
Array properties are special. I have added a page on my website to describe the topic: Reading and writing array properties.
Summarizing from there, the way that the proxy-object model works, whenever you set a property on an object, the Office.js runtime has a hook into the setter and getter, which is used to intercept the call and add the command to the queue.
Let's take an example of a regular property first. Per the above, whenever you set something like range.format.fill.color = "red", the setter for the color property intercepts the request and internally adds a command into the queue to set the range fill color to red (to be dispatched with the next context.sync)
On the other hand, if all you had was var color = range.format.fill.color
(after a load and a sync, of course), the getter would fire instead of the setter, and the color variable would get the range's current fill color.
Now, that was regular properties. Whenever you set an element of the array, you are effectively accessing the array value as a getter. From a runtime perspective, this line is no different from a slightly more verbose version:
var array = range.values;
array[r][c] = '-';
Because the getter for range.values returns a perfectly plain JS array object, accessing it and then setting its value does nothing to propagate it back to the original Range object.
If you want the values to get reflected back, the best thing is to get a reference to the array right after the sync (i.e., var array = range.values, just as above), then set the values on the array as needed, and then finally set it back to the object: range.values = array.
It means you could also modify the values array in place, and then assign the values property back to itself at the completion of the loop (range.values = range.values). However, this looks awkward, as if it’s a no-op, whereas in reality it is not. So personally, I prefer to retrieve the array at the beginning and assign it to its own variable, then do any necessary modifications, and finally set the full array back.
UPDATE to clarify the above:
To be very clear, the arrays returned by accessing the .values, .formulas, etc., ARE pure vanilla JS arrays. That's actually the crux of the problem: that in order for Office.js to return pure objects, it means that those pure objects can't be "spiked" with the ability to reflect changes.
For what it's worth, we actually have an upcoming feature that should be rolling out in a month or two, where we will be introducing an object.set syntax, as in:
range.set({
values: [[1, 2], [3, 4]],
format: {
fill: {
color: "purple"
}
}
}
This will make it more convenient to set multiple properties on the same object, but it might also make the array properties easier to deal with.

Groovy - Collection only returns a single value

I've got a small code snippet that loops through a node and grabs all its properties.
I can get this to work if I set one variable to grab the properties values (except it has a weird [] surrounding it). But I don't want redundant code so I'm trying to set multiple properties inside the loop, except all that returns is a single value, it's not looping around all the nodes.
WORKING
String selectNodeLabel = null
selectNodeLabel = JcrUtils.getChildNodes("links").collect{
it.getProperty("label").getString()
}
SINGLE VALUE
String selectNodeLabel = null
String selectNodeMeta = null
String selectNodeFooter= null
String topicNode = null
topicNode = JcrUtils.getChildNodes("links").collect{
selectNodeLabel = it.getProperty("label").getString()
selectNodeMeta = it.getProperty("meta").getString()
selectNodeFooter = it.getProperty("footer").getString()
}
Thanks for any help!
Try:
def nodeList = JcrUtils.getChildNodes("links").collect{
[ selectNodeLabel : it.getProperty("label").getString()
selectNodeMeta : it.getProperty("meta").getString()
selectNodeFooter : it.getProperty("footer").getString() ]
}
Then, nodeList will be a list of Maps, so you could do:
println nodeList*.selectNodeLabel
To print all the selectNodeLabel values for example.
To explain the problems with your code... Collect creates a list of the elements returned by the closure. What your SINGLE VALUE code is doing is overwriting the values in the selectNode... variables, and then setting topicNode to the value returned from the closure for each element in JcrUtils.getChildNodes("links").
For this case, topicNode will contain a List of it.getProperty("footer").getString() (as it is the last line in the Closure

Resources