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

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.

Related

Declare a nodejs const from a variable?

Is it possible to programmatically declare a nodejs const from a variable (string?)
let myConsts = ["const1","const2","const3"];
myConsts.forEach(function(label){
defineConst(label,"value"); // I need this function
})
defineConst should define a const, something like the PHP "define" function, but for nodejs
No, you can't really do that in Javascript. For a bit, I thought maybe you could hack it with eval() which is pretty much always the wrong way to solve a programming problem, but even eval() won't introduce a new const variable to the current scope. It will introduce a new var variable to the current scope as in this:
// dynamic variable name
let varName = "test";
// create variable in the current scope
eval("var " + varName + " = 4;");
// see if that variable exists and has the expected value
console.log(test);
But, alas you can't do this with const. You can read more about why here: Define const variable using eval().
Whatever programming problem you are trying to solve can likely be solved in a much better way since you really shouldn't be introducing dynamically named local variables. It's much better to use something like a Map object or a regular object with dynamically named properties in order to keep track of values with dynamic names to them.
If you shared the actual programming problem you're trying to solve (rather than your attempted solution), we could advise further on the best code for that particular problem.
Here's an example of the ability to store dynamically named properties on an object:
let base = {};
// dynamic property name (any string value in this variable)
let varName = "test";
// set property value with dynamic property name
base[varName] = "Hello";
// can reference it either way
console.log(base[varName]);
console.log(base.test);
Or, it can be done using a Map object:
let base = new Map();
// dynamic Map element key (any string value in this variable)
let varName = "test";
// set Map element with dynamic key
base.set(varName, "Hello");
// can reference it either way by the key
console.log(base.get(varName));
console.log(base.get("test"));

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.

"new Set" is returning an empty set in nodejs

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!

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

What is wrong in this LINQ Query, getting compile error

I have a list AllIDs:
List<IAddress> AllIDs = new List<IAddress>();
I want to do substring operation on a member field AddressId based on a character "_".
I am using below LINQ query but getting compilation error:
AllIDs= AllIDs.Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_"))
.Select(s => s.AddressId.Substring(s.AddressId.IndexOf("_")))
.ToList();
Error:
Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<MyCompany.Common.Users.IAddress>'
AllIDs is a list of IAddress but you are selecting a string. The compiler is complaining it cannot convert a List<string> to a List<IAddress>. Did you mean the following instead?
var substrings = AllIDs.Where(...).Select(...).ToList();
If you want to put them back into Address objects (assuming you have an Address class in addition to your IAddress interface), you can do something like this (assuming the constructor for Address is in place):
AllIDs = AllIDs.Where(...).Select(new Address(s.AddressID.Substring(s.AddressID.IndexOf("_")))).ToList();
You should also look at using query syntax for LINQ instead of method syntax, it can clean up and improve the readability of a lot of queries like this. Your original (unmodified) query is roughly equivalent to this:
var substrings = from a in AllIDs
let id = a.AddressId
let idx = id.IndexOf("_")
where id.Length >= idx
select id.Substring(idx);
Though this is really just a style thing, and this compiles to the same thing as the original. One slight difference is that you only have to call String.IndexOf() one per entry, instead of twice per entry. let is your friend.
Maybe this?
var boundable =
from s id in AllIDs
where s.AddressId.Length >= s.AddressId.IndexOf("_")
select new { AddressId = s.AddressId.Substring(s.AddressId.IndexOf("_")) };
boundable = boundable.ToList();

Resources