JSON structure in javascript [closed] - javascript

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 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks

What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));

These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)

Related

Is there a way that this is possible? I am trying to find a value of a var constructed by other variables [closed]

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 2 years ago.
Improve this question
This is a little bit of my code. I took out the complex parts. It is all on the script tag.
var trueenemyscoutx = '_2'
var tryeenemyscouty = '2'
var type_22 = "none"
var move1;
enemymove = "type" + trueenemyscoutx + trueenemyscouty;
var move1 = (enemymove.valueOf()).valueOf()
In the post, enemymove is a string constructed by concatenating "type" and two other variables, each of which is also a string.
The resultant string contains no information about the variables used and so the general answer to the question is no, it is not possible using the approach taken.
Obvious alternatives include:
Keep move a string, but use a separator (e.g. colon, comma or space) between component substrings. This allows extracting an array of the components using move.split(separator).
Use an array or simple object to hold move information instead of a string in the first place.

Why this for loop on Javascript is worse than pattern matching? [closed]

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 6 years ago.
Improve this question
I needed to create a lot of entities in arrays at my job, and some guy said to me use this library to use "pattern matching" in my pull request instead creating manually the arrays an populating it.
We have to create a lot of things, eg. of user:
function createUser(id){
return {
id: id
}
}
var users = createStuff(createUser, 50);
what I did to populate:
function createStuff(createFunction, howManyTimes){
var createdStuffs = [];
for(var i = 0; i < howManyTimes; i++){
createdStuffs.push(createFunction(i));
}
return createdStuffs;
}
what he asked me to do with pattern matching:
function createStuff(createFunction, howManyTimes){
return howManyTimes.matches(
(x = 0) => [],
(x) => [createFunction(x)].concat(createStuff(createFunction, x - 1))
)
}
What is the benefits about this pattern matching? I do understand the recursive calling on his example which replaces the for loop, but I think my example is easier to read though all the creation logic is basically written at a single line at his example.
I'm asking explanations about this and most people are telling me "it's better because is functional and have less moving parts", is this really true? I don't agree with him and I'd like explanations or arguments to tell he's wrong
Your colleague has taken the quite correct premise that immutability and a functional style is beneficial and drawn a very incorrect conclusion that any immutable solution employing a functional style is superior. Readability is important and possible in any paradigm.
A proper functional solution using underscore.js with all the benefits and none of the eye-gouging readability issues would look like:
var users = _.map(_.range(howManyTimes), createUser);

Which is the standard in JSON: Objects inside Objects, or Objects inside Array [closed]

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.

Using String/Array String as Variable name in JavaScript? [closed]

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 8 years ago.
Improve this question
I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!
So basicly what I'm trying to do is this:
var "TempVar"+Array[i] = Something;
also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.
Sorry about my bad English, its terribly late and English is not my native language.
Also notice that I'm new to JavaScript so don't hate me too hard...
Basically youre going to need to do this:
//Create an empty object
var myObject = {};
for(var i=0; i<Array.length;i++)
{
//Add properties to the object
myObject["TempVar"+Array[i]] = Something;
}
Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:
myObject.property = "Blah";
Or you could access the property like an array:
myObject["property"] = "Blah";
Both perform the same operation.

Local Variable usage reasoning [closed]

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 have lot enough functions, which look like:
var functionName = function(e) {
//
};
where all the parameters are getting passed in in a single container e. Most times values are simple values (no functions), ex.:
{ parameter1: 1, parameter2: "Name", parameter3:{ subParameter1: "A"}}
But there're times when I pass in functions as in: { p2:function(){...} }
I have two options when it comes to utilising parameter values:
Options 1: get parameter values from the chain, starting from e: e.parameter1, e.parameter3.subParameter1 etc.
Option 2: use cached parameter values:
var parameter1 = e.parameter1;
var subParameter1 = e.parameter3.subParameter1;
The second option improves readability but increases the number of vars and the size of the code base. On another hand it's much drier when using long chains, i.e. e.p1.p2.p3 etc.
What reasoning should I use for choosing between those two options?
**Update 1 - the question sounds quite subjective, let me re-prase it.**
I don't mind using chains all the way, no local vars codebase is smaller, I can always figure out what's what, are the any cases when caching is a must?
A combination, based on depth(e.p1 vs e.p1.sp2.ssp3) and frequency of use. Deeper sub-properties and high usage of any sub-property both benefit from caching.
Nested property look ups can get costly, and caching the value after executing the look up once is valuable if you're going to use it a lot. This is only more efficient if you're accessing a particular property on the chain more than once, and the more you access it, the more you benefit from caching.
If you only have one level deep(e.p1, e.p2, e.p3) and you're only looking up each property value once, don't bother.
If you're accessing e.p1.sp2.ssp3 all throughout your function, cache it for sure.

Categories

Resources