Reading an Array correctly - node.js

I have a json file called "GuideDB" which contains data about somethings.
GuildDB.json
{"GuideID":{"prefix":"","DJ":null,"Roles":""}}
Basically I want to access the data "Roles" in a way I can manage each element in that line, e.g.:
const myArray = GuildDB.Roles; //GuildDB.Roles is the only way to access that line.
myArray.forEach(element => {
console.log("<#&" + element + ">")
});
this code gives the error "forEach", because the array is not correctly formated.
How do I add Items in GuildDB.Roles?
client.database.guild.set(message.guild.id, {
prefix: GuildDB.prefix,
DJ: GuildDB.DJ,
Roles: GuildDB.Roles + ", " + createdRole.id, //Bug: First run always writes the comma first.
});
This will result the following:
{"GuideID":{"prefix":"","DJ":null,"Roles":", 123, 1234, 12345, 123456"}}
Which is not what I want.. and I don't care how this looks, I need to make it easy access to read/manage that data of Roles.
Hope anyone can help..

You can do something like this to convert Roles into array first and then use forEach loop on it.
const myArray = GuildDB.Roles.split(",");

Related

How can I get the multiple subchild objects from json using nodejs?

I am trying to fetch the specifice object from my json files. For now I can fetch any tag instead of the "p" tag from it. you can please have look at the screenshot I have attached.
Click to open the json file
this is how I'm trying to fetch p tag:
'use strict';
const fs = require('fs');
var data = JSON.parse(fs.readFileSync('./me.json'));
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral.p);
});
This is a weird way of organizing your block, I recommend rewriting/reorganizing the JSON so it is more easily accessible.
There are a few things you have to know before this answer makes sense:
Array indexes
[] resembles an array, you can access each index by doing array[index], for example:
let arr = ['zero', 'one', 'two'];
console.log(arr[0]); //expected output: 'zero'
Bracket Notation
In JavaScript, there are two ways to access a variable's value, either by dot notation or bracket notation. As far as I know, the only differences these have are just the ability to use dynamic input and characters you can't usually use inside a variable's name, for example:
let obj = {
var1: "this is variable1",
var2: {
var3: "this is variable3 inside variable2"
}
}
console.log(obj.var1) //expected output: "this is variable1"
console.log(obj[`var1`]) // expected output: "this is variable1"
console.log(obj.var2.var3) //expected output: "this is variable3 inside variable2"
console.log(obj[`var2`].var3) // expected output: "this is variable3 inside variable2"
console.log(obj[`var2`]["var3"]) // expected output: "this is variable3 inside variable2"
Bracket notation also works inside objects, thus why the variable names inside as a string, like "Document", works.
let obj2 = {
"var1": 1,
["var2"]: 2,
var3: 3
};
console.log(obj2["var1"]) // expected output: 1
// console.log(obj2"var1") is INVALID and does not work
console.log(obj2["var2"]) // expected output: 2
console.log(obj2.var3) // expected output: 3
Coming to the solution
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral[0].p)
});
This returns ["ASDFDSFDSFSD"], if we wanted to use it as a string and not an array (remember the brackets) then we would access the first index of the array. This would be done by adding [0] at the end.
❕ Solution
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral[0].p[0])
});
Future Information
About stackoverflow, next time, please share code via code blocks and not screenshots. Thank you for coming to ask your question, we just want it to be easier for us to both understand and access the code! I had to type the whole thing out myself, which could've been easily avoided by just copy/paste-ing the code. If you don't know how to do certain things in the textbox, see the formatting help page.

Write json content in json format to a new file in Node js

Goal: To write the file content in json format using Node js. Upon opening the file manually, content should be displayed in json format
I tried both fs-extra module functions - outputJsonSync or writeFileSync to write json content to a file. They write the content inline as below
{"a":"1", "b":"2"}
However, I would like to see the content as below when I open the file manually:
{
"a" : "1",
"b" : "2"
}
I tried jsome and pretty-data on the data as follows:
fs.outputJsonSync(jsome(data))
fs.outputJsonSync(pd.json(data))
They also write data inline only with extra \ or \n and tabs added to the data but doesn't open in formatted style.
Any inputs are highly appreciated. Thanks!
[Update]
Other scenario:
const obj = {"a":"1", "b":"2"}
var string = "abc" + "splitIt" + obj
doSomething(string)
And inside the function implementation:
doSomething(string){
var arr = string.split("splitIt")
var stringToWrite = JSON.stringify(arr[1], null, ' ').replace(/: "(?:[^"]+|\\")*"$/, ' $&')
fs.writeFileSync(filePath, stringToWrite)
}
Following output is displayed when I open the file:
"[object Object]"
Once you have the object, you can specify a replacer function to separate each key-value pair by a newline, then use a regular expression to trim the leading spaces, then use another regular expression to insert a space before the : of a key-value pair. Then, just write the formatted string to a file:
const obj = {"a":"1", "b":"2"};
const stringToWrite = JSON.stringify(obj, null, ' ')
// Trim leading spaces:
.replace(/^ +/gm, '')
// Add a space after every key, before the `:`:
.replace(/: "(?:[^"]+|\\")*",?$/gm, ' $&');
console.log(stringToWrite);
Though, you may find the leading spaces more readable:
const obj = {"a":"1", "b":"2"};
const stringToWrite = JSON.stringify(obj, null, ' ')
// Add a space after every key, before the `:`:
.replace(/: "(?:[^"]+|\\")*",?$/gm, ' $&');
console.log(stringToWrite);
JSON.stringify, has two optional parameters, the first one being a replacer function, the second one(What you want) is for spacing.
const obj = {"a":"1", "b":"2"}
console.log(JSON.stringify(obj, null, 2))
This will give you:
{
"a": "1",
"b": "2"
}

Firebase wriitng a "0" rather than the actual variable content

I'm updating a value in my database under a field called message threads. Under that thread I want to store the keys of all the users and in that key I want their picture. From this I've constructed a loop containing the following:
firebase.database().ref('users/' + userUID + '/messageThreads/' + newThreadID).update({
"date": currentDate.getTime(),
"lastMessage": "",
"read": false,
"isGroup": true
});
console.log(groupUID);
firebase.database().ref('users/' + userUID + '/messageThreads/' + newThreadID + "/" + "userUID").update({
[groupUID]: [groupPic]
});
For some reason, under the database instead of the value of groupUID, it puts a zero.
Any suggestions?
The "0" was the array index (because you were pushing in the array [groupPic] instead of a plain value. That's easy, just use groupPic.
The dynamic key name is a bit trickier: the easiest way is to define the object ahead of time, before setting it in firebase:
var newVal = {};
newVal[groupUID] = groupPic;
firebase.database().ref('path/to/ref').update(newVal);
Or:
So I learned something today! (Thanks!) And now I understand how you wound up unintentionally using an array in the first place.
The shorthand notation you were using for the key was just fine, I'd just never seen it before. So this would work too, it's equivalent to the above (if potentially a bit more confusing to read, because it looks like it's going to be an array):
firebase.database().ref('path/to/ref').update({[groupUID]: groupPic});

Autocomplete function with underscore/JS

what is the proper way to implement an autocomplete search with undescore?
i have a simple array (cities) and a text input field ($.autocomplete). when the user enters the first letters in the auto-complete textfield, it should output an array with all the cities starting with the entered letters (term).
cities:
["Graz","Hamburg","Innsbruck","Linz","München","Other","Salzburg","Wien"]
eventlistener:
$.autocomplete.addEventListener("change", function(e){
var cities = cities_array;
var term = $.autocomplete.value;
var results = _.filter(cities, function (city){
return
});
console.log(results + "this is results");
});
I’ve tried it with _.contains, but it only returns the city when its a complete match (e.g Graz is only output when „Graz“ is entered but not when „Gr“ is entered).
the _.filter/._select collection at http://underscorejs.org/docs/underscore.html are not very clear for me and the closest i found here is filtering JSON using underscore.
but i don’t understand the indexOf part.
thx for any suggestions!
By using #filter and #indexOf, you can get quite close to a pretty decent autocomplete.
What #indexOf does is that it checks the string if it contains the inputVal.
If it does not contain it it'll return -1 therefore our predicate below will work without fail.
Another small trick here is that you (read I) wanted it to be possible to search for s and get a hit for Innsbruck and Salzburg alike therefore I threw in #toLowerCase so that you always search in lower case.
return _.filter(cities, function(city) {
return city.toLowerCase().indexOf(inputVal.toLowerCase()) >= 0;
});

Getting the property of an associative array given as an escaped string

I have an array that looks like this:
[{"x": "someValue",
"y" : "{\"iWantThisValue\":\"a\", \"otherVal2\":\"b\"}"}]
I want to get the value of "iWantThisValue". On the view, I have #{JSON.parse(myArray.y)}. If I try to put something like .iWantThisValue after it, nothing is printed out. Is this a correct step to getting it? Where do I go from here?
You're pretty close, but you need to subscript the array.
var myArray = [
{
"x": "someValue",
"y" : "{\"iWantThisValue\":\"a\", \"otherVal2\":\"b\"}"
}
];
console.log( JSON.parse( myArray[0].y ).iWantThisValue );
Logs a.
Of course in real code, you probably wouldn't just be doing [0] to access an array element, but would probably be looping through the array? Either way, you'd still need to use myArray[index] where index is 0 in this example.
Also, in the interest of clarity, JavaScript does not have anything called an "associative array". It has arrays and it has objects. In your example, myArray is an array of one element. That element is an object which has x and y properties.

Resources