Separate big array from main component to a new file - javascript

I'm new in the front end world, and I currently working on Angular project with typescript, and I created an array in order to assign to an object, so I have something like this in my TS component:
formOptions = []
ngOnInit() {
this.formOptions = [{
id: 1,
description: 'First name'
},
{
id: 2,
description: 'Middle name'
}, {
id: 3,
description: 'Last name'
}...etc
}
As you can see the array it's going to be supper big, is there a way to move the array to separate file, then import it and just assign the object? If so, where is the common path to save this path of files and what extension I should use for it?

Try storing the array in a separate .json file. Then use fetch to load the file and parse the JSON. JSON is Javascript Object Notation and it will take an array (or object) exactly as you have it laid out in your code.
[{
id: 1,
description: 'First name'
},
{
id: 2,
description: 'Middle name'
}, {
id: 3,
description: 'Last name'
}...etc
}]
The first example at MDN does exactly what I describe.

Related

Why is my JSON object showing [Array] instead of the data in javascript after reformatting?

Currently I am trying to create a JSON object in java script which has an additional array containing all of the data that I currently posses:
src is a JSON object which before any code is run is equal to:
[
{
_id: new ObjectId("629ac43586b27bfd70337d06"),
Title: 'Test Poll',
Option: [ 'Test Option 1', 'Test Option 2', 'Test Option 3' ]
},
{
_id: new ObjectId("629afc9286b27bfd70337d09"),
Title: 'Test Poll 2',
Option: [ 'Test Option 1' ]
}
]
I need to reformat this object so that it is contained within a separate array which I am currently attempting to do with this line:
var context = { poll:src };
This results in a reformatting of the JSON object which I do not understand, after running this code context contains:
poll: [
{
_id: new ObjectId("629ac43586b27bfd70337d06"),
Title: 'Test Poll',
Option: [Array]
},
{
_id: new ObjectId("629afc9286b27bfd70337d09"),
Title: 'Test Poll 2',
Option: [Array]
}
]
It gets rid of the Option arrays and replaces them with [Array]. I need to keep these arrays and I am not sure what to change to fix this as I have tried looking elsewhere for answers. Does anyone have an idea of what is going on here?
Ok they are arrays I am just too new to realize that it would not print fully. I was attempting to use handlebars on these Option arrays to print the list and I was forgetting to use the implicit this for the variable name instead of just 'Option'.
Problem solved.

Move properties in objects according to their index

I've been trying to do this, and I've looked for the answer everywhere but no one seems to know or have the same problem.
What I want to do is: I have an array that looks like this
const myArray = [
{
nombre: 'String',
definicion: 'Whatever.',
duracion: 'Blah',
id: "Blah",
},
{
nombre: 'Name',
definicion: 'Short description.',
duracion: 'time',
id: "whatever again",
},
{
nombre: 'hello',
definicion: 'this is descripciĆ³n.',
duracion: 'time',
id: "the end",
},
I used map return (item. nombre, item. definicion, etc.) and have them separated in different divs, so I wanted to do nombre.onclick (CSS transition so that the its definition will be shown) but its not working. It either shows all definitions or none. Sometimes it shows one definition 3 times ( or the number of objects in the array)

Efficient algorithm / recursive function to nest items from a list

I'm currently implementing my own commenting system. Unfortunately Disqus or any other comment platform doesn't meet my requirements.
I use NodeJS and MongoDB as backend. I need to run basically two queries on my database:
Get all comments by a topic/slug
Get all comments by a user
One can comment to an topic or reply to a comment.
Hey, cool post # top lvl comment
Thanks! # reply to comment
Foo Bar! # reply to reply
and so on...
So my database schema looks like
{
id: ObjectId,
text: string,
author: { id: ObjectId, name: string },
parent: nullable ObjectId,
slug: string/number/whatever
}
If parent is null it's a top level comment, otherwise it's a reply.
Pretty easy so far, right? The problem I do have now is displaying comments below posts. When there would be only top level comments it would be easy. Just get all comments for one specific slug, sort them by date/rating/... and compile them with my HTML View Engine.
But there are in fact replies and I'm just stuck at the point where I need to organize my structure. I want to nest replies into comments within my list
Original list (simplified)
[
{ id: 1, text: 'foo', parent: null },
{ id: 2, text: 'bar', parent: 1 },
// ...
]
Expected Output
[
{ id: 1, text: 'foo', replies: [
{ id: 2, text: 'bar' },
] },
]
I've tried creating my expected output with a recursive function which got very weird tho. Unless that it wouldn't be very efficient. So since I'm really getting frustrated and kinda feeling stupid not solving this problem I've decided to ask for your help SO.
The actual problem I want to solve: How do I render my comments, that they are properly nested etc.
The question I'm going to ask: How do I organize my flat structure in an efficient way to solve the above described problem?
Here's one approach with linear complexity:
var comments = [{
id: 3,
text: 'second',
parent: 1
}, {
id: 1,
text: 'root',
parent: null
}, {
id: 2,
text: 'first',
parent: 1
}, {
id: 5,
text: 'another first',
parent: 4
}, {
id: 4,
text: 'another root',
parent: null
}];
var nodes = {};
//insert artificial root node
nodes[-1] = {
text: 'Fake root',
replies: []
};
//index nodes by their id
comments.forEach(function(item) {
if (item.parent == null) {
item.parent = -1;
}
nodes[item.id] = item;
item.replies = [];
});
//put items into parent replies
comments.forEach(function(item) {
var parent = nodes[item.parent];
parent.replies.push(item);
});
//root node replies are top level comments
console.log(nodes[-1].replies);

Convert JSON into Array of JavaScript Objects

I got a JSON result from PHP that looks like this below. I need to convert it into an array of objects like shown at the bottom.
How can I achieve this?
What I have
Milestones JSON
[
{
"id":0,
"name":"None"
},
{
"id":1,
"name":"Milestone 1"
},
{
"id":2,
"name":"Milestone 2"
},
{
"id":3,
"name":"Milestone 3"
},
{
"id":4,
"name":"Milestone 4"
}
]
What I need
Milestones Array Of OBjects
var taskMilestonesArray = [{
id: 0,
name: 'None',
},
{
id: 1,
name: 'Milestone 1',
},
{
id: 2,
name: 'Milestone 2',
},
{
id: 3,
name: 'Milestone 3',
},
{
id: 4,
name: 'Milestone 4',
}];
UPDATE
I just realized they are both in almost exact same format already. I just need to pass the array of objects into a library that expects it to be in that format and I don't think I can pass the JSON in.
If you have that JSON in a string (for the sake of the example, I will assume you have a variable named yourJsonString that holds your json), you can parse it:
var taskMilestonesArray = JSON.parse(yourJsonString);
Use JSON.parse api to convert json string to the javascript object.
var taskMilestonesArray = JSON.parse('< milestones json string >');

JSON / Jade - Cannot output JSON variable to Jade template

I'm passing some JSON data to a Jade template, but can't seem to print the JSON data to my Jade template. This is an example of the JSON which is stored and passed to the Jade template:
{ name: 'Team 1',
_id: 5134d71192cf972226000003,
__v: 0,
key: 1362417425623 }
It is passed through to the Jade template like so:
res.render('tournamentDetails', { 'tournamentData' : tournamentData, seedsSerialized : JSON.stringify(tournamentData.teams) } );
The format of the Jade template is:
script(type='text/javascript')
var seeds = [#{tournamentData.teams}];
I'm trying to access this variable seeds in a seperate JavaScript file, but cannot seem to access them. I have been testing using alert to test what is in seeds in the JavaScript file and it is not the teams.
This is the generated HTML from the Jade too:
var seeds = [{ name: 'Team 1',
_id: 5134d71192cf972226000003,
__v: 0,
key: 1362417425623 },{ name: 'Team 2',
_id: 5139dc66b48da58d0e000001,
__v: 0,
key: 1362746470498 },{ name: 'Team 3',
_id: 5139dda45f1598440f000001,
__v: 0,
key: 1362746788314 },{ name: 'Team 4',
_id: 513b2c66cfd50dce11000001,
__v: 0,
key: 1362832486554 }];
How would I access the teams in a JavaScript file? I am wanting to output the names of the teams to the Jade template.
This may not be an answer exactly, but it was too long for a comment...
Look at this jsfiddle: http://jsfiddle.net/KvXTA/
var seeds = [{ name: 'Team 1',
_id: 5134d71192cf972226000003,
__v: 0,
key: 1362417425623 },{ name: 'Team 2',
_id: 5139dc66b48da58d0e000001,
__v: 0,
key: 1362746470498 },{ name: 'Team 3',
_id: 5139dda45f1598440f000001,
__v: 0,
key: 1362746788314 },{ name: 'Team 4',
_id: 513b2c66cfd50dce11000001,
__v: 0,
key: 1362832486554 }];
console.log(seeds);
notice how the console outputs
Uncaught SyntaxError: Unexpected token ILLEGAL
That's because of the _id fields. I'm surprised you say that the serialized version has the same problem, since it should have surrounded the ID's in quotes. If you don't need the ID's at all, you can get rid of them in the serialized version by using a replacer function.
var seedsSerialized = JSON.stringify(teams, function (key, val) {
return key === '_id' ? undefined : val;
);
res.render('tournamentDetails', { seedsSerialized: seedsSerialized });
Then use that serialized version to initialize seeds in the template.
script
var seeds = !{seedsSerialized};
My earlier comment about order of including scripts wasn't a concern that maybe another file was creating a seeds variable, it was that you might have been including a file which used seeds before seeds was actually declared.
For example:
<script src='logSeeds.js'></script>
<script>
var seeds = [ ... ];
</script>
where logSeeds.js is:
console.log(seeds);
would obviously output undefined since seeds hasn't been declared yet. It was just a thought, not necessarily your situation.

Categories

Resources