Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I got this code snippet from jest documentation.
In the example, one of the variables is named ceiling.height and is the only variable with a dot . in the name. What would be the purpose of using variables with a dot in the name such that it warrants this example in the documentation?
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
'nice.oven': true,
},
'ceiling.height': 2,
};
The purpose would be to store nested objects in a flat format, ie. a database table.
You could use something like dottie.js to transform this flat object into a nested object
const values = {
'user.name': 'Gummy Bear',
'user.email': 'gummybear#candymountain.com',
'user.professional.title': 'King',
'user.professional.employer': 'Candy Mountain'
};
const transformed = dottie.transform(values);
We would now find this to be the value of transformed
{
user: {
name: 'Gummy Bear',
email: 'gummybear#candymountain.com',
professional: {
title: 'King',
employer: 'Candy Mountain'
}
}
}
Why they use it like that in the example seems to be so that they can provide an example (below) on how to access these kinds of variable names. Imagine that you wanted the .toHaveProperty(keyPath value?) function from the Jest docs to operate on a property in the values object from the above example. This shows you how you might use this function with such a property.
// Referencing keys with dot in the key itself
expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
Unless you have a very good reason, using these kinds of variable names is not a best practice and I would not recommend it. That said, while a variable name with a . character is not able to be used with dot syntax:
houseForSale.ceiling.height = undefined
It is still accessible with bracket syntax:
houseForSale['ceiling.height'] = 2
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Instead of using associative arrays (objects), what is the best way to associate two values so they are always associated and can both be accessed as separate values? Associative arrays are annoying because their order isn't guaranteed and you can't access them using indexes.
I could create two separate arrays but if I randomize their order for display their association would not match, and if they are separate in code there is a good chance I can make a mistake when recording their values, putting them in the wrong order so they don't perfectly match up.
In Javascript you can use multidimensional arrays:
var data = [
[1, 2],
[3, 4]
];
data[0][0]; // get '1'
data[0][1]; // get '2'
Also if you need to associate data in a more abstract way, ES6 has WeakMaps:
var wm = new WeakMap();
var x = document.createElement("div");
wm.set(x, {foo: 1, bar: 7});
console.log(wm.get(x).bar) // get '7' from object you associated to HTMLElement
I do not now which kind of data you should store but maybe you could try to store data in a single variable in this way:
var data = [];
data[0] = "Test" + "|" + Value;
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I did a little research, and the best answer I found is:
function overloading in js
Top 10 answers did gave me some hints and clues, but not the consistent way how to handle those situations in general.
Let's take a question a little further:
What if I am making API for someone else. That should give you the answer to following questions:
Why am I doing this?
JS doesn't have overriding in strict sense (yes I am aware, not the point)
Pass the object with optional parameters (Would prefer it, it's not up to me)
Specific solutions that assume types, fixed number of parameters, single values etc.
Some of the functions have to take many optional parameters (and some non-optional ones). So the function looks something like:
var f = function (unopt1, unopt2, op1, op2, op3) {
// code
}
The unoptX parameters are not optional.
The opX parameters are optional (in a sense they can be equal to 1 value from fixed set or values or not passed to function at all).
So function can be called in any of the following ways:
f("z", "b")
f("a", "b", 1, "ff");
f("a", "b", "ff", "hic");
f("a", "b", "ff", "no-hic");
etc.
Obviously, optional parameters each can have certain values, let's say they are listed in a certain order. And ofc. function behaves differently depending on the parameters
What would be your reccomended approach on this? Multiple ones are fine, prefferably you will point out what are ups/downs of certain approach over the other.
Use the spread operator as the argument:
function f(...args){
switch(args.length){
case 1:
get()
case 2:
set()
default:
setWithOptions()
}
}
Use an "options" object or ES6 "rest parameters"
var f = function (unopt1, unopt2, opts) {
opts = opts || {};
// later... if( opts.yourOptionalArg )
}
ES6 Rest Parameters
var f = function (unopt1, unopt2, ...args) {
console.log(args)
var firstOptionalArg = args[0];
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Each ArrayItem contains no. of Property like Id, Name, Description etc
But we want to Fetch ArrayItem with Help of Name Property .
So Please give me code suggestion in Jquery or backbonejs without using for loop.
If you are using BackboneJS, you already have UnderscoreJS installed. Underscore has several methods for searching through a collection. For instance, using _.findWhere(...):
var myArray = [ ... ];
var helpItem = _.findWhere(myArray, { name: 'help' });
This would return the first entry in the array that has a name property equal to 'help'. _.findWhere(...) can match multiple properties too. If you want to find an item with something other than direct equality of properties, you can use _.find(...):
var overTwentyOne = _.find(myArray, function(entry) {
return entry.age > 21;
});
This would return the first entry in the array whose age property was greater than 21.
Note also that most of the list-centric methods in Underscore are automatically mixed into all Backbone.Collection instances. So if you were searching through a Collection, the above findWhere(...) example could be more simply written as:
var helpItem = collection.findWhere({ name: 'help'});
This would return the first Backbone.Model instance from collection that had a property name equal to help.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've a question, not in how to do something but rather in the "standard" or "accepted" way.
Which of this is the preferred one, and why?
var data = {
employees:{
"John Williams":{
...
},
"Susane Rodgers":{
...
},
"Clint Eastwood":{
...
}
}
};
var data = {
employees:[
{
name:"John Williams",...
},
{
name:"Susane Rodgers",...
},
{
name:"Clint Eastwood",...
}
]
};
This is basically your data structure. The only thing that is "accepted" or preferred in data structures is simplicity. However many times it turns out that an API or old code has been written in a way that forces you to use a certain data structure. In your case, the first example suggests that there will not be employees with the same name, which is unacceptable since people with the same names exist and thus your application has a potential weakness. So the second example would be the better choice in that case.
Similar to the other answer, something else to consider about your data structure is how you plan on using the data. Depending on what your insertion / retrieval / removal / etc needs are, you may decide that one data structure is easier for you to use. Because you're using objects or arrays, you'll have access to different methods for you to manipulate your data structure.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to define something like the following object structure, so I can populate it from a number of sources. What statements do I need to define it?
Offices[] is an open-ended array as is rel[] underneath it. All the elements are strings or maybe numbers.
Offices.name
Offices.desc
Offices.rel.type
Offices.rel.pt
First I would make Offices an array:
var Offices = [];
Then populate that with objects:
var obj = {
name: "test",
desc: "Some description",
rel: []
}
Offices.push(obj);
Now you have your array (Offices) populated with one object, so you could access it via Offices[0].desc -- you can also populate the rel array with Offices[0].rel.push(anotherObj)
If i understand correctly, you want to place multiple objects of the same type inside the Offices array. In order to easily build multiple objects of the same type you could use a constructor:
function Office(name, desc, rel){
this.name = name;
this.desc = desc;
this.rel = rel;
}
Now you can declare an array to hold instances of the above type:
var offices = [];
And you can add new instances like this:
offices.push(new Office('John', 'good guy', []));
You can apply the same idea to the rel array to enforce the structure of the objects, or simply use object and array literals:
offices.push(new Office('John', 'good guy', [{ type : 'M', pt : 3 }, { type : 'Q', pt : 2 }]);