Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I seem to be having trouble accessing individual elements of a json array. Given this code:
json_array=JSON.parse(data);
console.log(json_array);
console.log(json_array.title);
console.log(json_array.requester);
console.log(json_array.none);
This is the output:
Array(3)
0: {requester: false}
1: {title: false}
2: {none: true}
length: 3
[[Prototype]]: Array(0)
undefined
undefined
undefined
Obviously I am somehow accessing the individual elements incorrectly. What am I missing? TIA.
It seems like you forget the index when accessing array
console.log(json_array[0].title);
console.log(json_array[1].requester);
console.log(json_array[2].none);
You need to access json_array this way:
console.log(json_array);
console.log(json_array[0].title);
console.log(json_array[1].requester);
console.log(json_array[2].none);
This is because your json_array is an array with three objects, like this:
[
{
"title": ""
},
{
"requester": ""
},
"none": ""
]
An alternative solution would be to destructure your array into individual variables,which you can use accordingly :
const arr = [
{title:"title"},
{requester:"requester"},
{none:"none"}
]
const [title,requester,none] = arr
console.log(title,requester,none)
Please try this:
json_array = Object.assign([], json_array).reduce((a, b)
=> Object.assign(a, b), {});
console.log(json_array);
console.log(json_array.title);
console.log(json_array.requester);
console.log(json_array.none);
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 9 months ago.
Improve this question
To check if an element exist in an array, which method is better? Are there any other ways to do a boolean check?
type ObjType = {
name: string
}
let privileges: ObjType[] = [{ name: "ROLE_USER" }, { name: "ROLE_ADMIN" }, { name: "ROLE_AUTHOR" }];
//method 1
const hasAdminPriv = privileges instanceof Array && privileges.find((ele: ObjType) => ele.name === "ROLE_ADMIN");
//method 2
const found = privileges instanceof Array && privileges.find((ele: ObjType) => ele.name === "ROLE_ADMIN") !== undefined;
//method 3
const privilSet = new Set<string>();
privileges.forEach((element: ObjType)=> privilegeSet.add(element.name));
//method 4
const privilegeSet2 = new Set<string>(privileges.map((element: ObjType) => element.name));
console.log(privilegeSet2.has("ROLE_ADMIN"));
That most likely depends on the way you want to use this.
The set conversion could be benefical, if you intend to query for multiple things at a time.
Maybe you'd rather use some for your query, if you're really only interested if a value is in the array and not for the rest of the object.
I'd also suggest having a look at includes as that can be exactly what you're looking for at least for trivial objects in an array.
That being said, if forced to use one of the provided methods, I'd argue that method 2 is best if you want to check for one value and method 4 if you either want to query multiple values or can cache the generated set for big arrays and relatively often asked queries.
Side note:
If your whole code is in typescript, I don't really see why you would use
privileges instanceof Array. Of course this may be necessary if the array comes from some js code or a file, but even then I'll argue that you should check the type when you receive the array and than assume that it is an array if it is typed that way.
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 3 years ago.
Improve this question
I have this array [ABC, QWE, XYZ]
I would like to turn it into ['ABC', 'QWE', 'XYZ']
When I try to manipulate values in the current array I get: ReferenceError: ABC is not defined
Any ideas on how should I do it?
Thanks!
Convert arrays element types:
Number to strings
var strArr = [1,2,3,4,5].map(String);
// Result: ["1","2","3","4","5"]
We can't do that directly but after little bit change you can do that...
So the current array you said like array [ABC, QWE, XYZ],
Lets design you keys in object first:
var obj = {
ABC:1, QWE:'somevalue', XYZ:new Date()
}
So I created object obj having your variables lets say the three variables, now lets convert:
var arr = [];
for (var key in obj){
console.log(key, obj[key]);
arr.push(String(key));
}
console.log(arr);// you will see the desire result.
Running example here : example
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'm creating a trivia game which will give the user 4 answer to pick from. Is using an array to include the question and the answer a good option for this game? and if so what is the proper way to create a nested array.
So... in js it's not a problem to make a nested array, but it is a problem if you're thinking of key => value type of array, in that case you need to use an object, you can foreach it's properties as you would with array IF you'd need to. You can store answer values in array (I've been there with exactly the same thing you want to do so trivia learning game), but you can always use objects and do something like that
var userAnswer = 'something',
item = {
question: 'what is a?'
answers: [ 'a', 'b', 'c' ]
validAnswer: 0;
}
if(userAnswer === item.answers[validAnswer]) {
console.log("is valid");
}
some other usage:
var userStats = {
status: 'alive',
makeDead: function() {
this.status = 'dead';
},
bringBackToLife: function() {
this.status = 'alive';
},
}
//then you can even do things like...
userStats.makeDead();
console.log(userStats); //user will be dead
userStats.bringBackToLife(); //user status will be alive
I mean you should be fine with array for keeping just question or question and (nested[[]]) array of answers, but then you're starting to play game of array[0] (should be question right?) array[3] (should be invalid answer?) and then what? if you still think your trivia game will never grow then you might stick to that solution, but if you think it might ever evolve just use objects to keep stuff organised.
update
Try to keep your objects small & dont make 'god' objects (look up SOLID rules), though if you want to let's say save/have a lesson containing some questions then you could have one big object containing a lot of small ones, i.e.
//you can make object to store some data and functions
var LessonItem = function(question){
this.question = question;
this.answers = [];
this.addAnswer = function(answer){
this.answers.push(answer);
};
};
//you dont need the 'valid' part if there's always just one valid option
var question1 = new LessonItem('What is?');
question1.addAnswer({text: 'It is something', valid: true });
question1.addAnswer({text: 'It is something not', valid: false });
question1.addAnswer({text: 'It is something 3', valid: true });
//and this would be our 'big' object, i.e. to save in json file or whatever
var lesson = {
lesson_subject: 'something',
lesson_repeat: 3,
lesson_score: 124,
lesson_items: [
question1,
//question2
]
};
console.log(lesson);
but yeah, you can have big 'object' to 'store' others, but avoid creating god-like one huge objects managing everything cause it will become hell with time :D as well im not sure if you're doing that but you can paste in your javascript in google chrome tools console and check if it's working right without reloading page... (for quick checks :))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an array like this one:
var data1 = [{ value: 'Afghan afghani', lubID: 'AFN' },{ value: 'Albanian lek', lubID: 'ALL' }];
What i want to do is to dynamically add items to data1 after it has been created. How can i do that?
Thank you.
Just like you push to any other array:
data1.push( { value: 'Something', lubID: 'Something Else'} );
If you're starting from an empty array, just define it first:
var data1 = [];
then start adding values using the push method I've shown you above.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
After a mysql query, I used the json_encode to convert the result of the query and I'm getting the following:
[
{"id":"1","map_id":"1","description":"This is Athens","lat":"37.77994127700315","lng":"23.665237426757812","title":"Athens"},
{"id":"2","map_id":"1","description":"This is Rome","lat":"41.9100711","lng":"12.5359979","title":"Rome"}
]
I want to convert this to JavaScript array but getting only the values. For example:
myArray = [
[1, 1, 'This is Athens', 37.77994127700315,23.665237426757812, 'Athens']
[2, 1, 'This is Rome', 41.9100711, 12.5359979, 'Rome']
]
I tried many solutions I found here, but I didn't found any solution to give me exactly an array like myArray.
Assuming :
var a = [{"id":"1","map_id":"1","description":"This is Athens","lat":"37.77994127700315","lng":"23.665237426757812","title":"Athens"},{"id":"2","map_id":"1","description":"This is Rome","lat":"41.9100711","lng":"12.5359979","title":"Rome"}];
You can use Array.prototype.map():
var myArray = a.map(function(e){
return [e.id, e.map_id, e.description, e.lat, e.lng, e.title];
});
Result:
[
["1","1","This is Athens","37.77994127700315","23.665237426757812","Athens"],
["2","1","This is Rome","41.9100711","12.5359979","Rome"]
]