json.stringify return value - json

I'm trying to get datatypes of a JSON.stringify to compare them.
I had used:
var id = d.patogeno;
alert(id);
But it tell the alert that is not defined.
I got this database:
var IDData = JSON.stringify([
["node/9837102", "node/26794", "Customer", "patongenoA", "1412451.0", 3, 520, "1412381"],
["node/9837102", "node/44210", "Customer", "patongenoB", "1436765.0", 2, 384, "1436693"],
]);
and the following function:
function createNodes(startnodes, endnodes, startnodetype, endnodetype, PayTime, TXN_COUNT, Total_Amt, SendTime) {
var node_set = new Set();
var links = [];
var nodetype = d3.set();
startnodes.forEach(function(src, i) {
var tgt = endnodes[i];
node_set.add({
id: src,
type: startnodetype[i]
});
node_set.add({
id: tgt,
type: endnodetype[i]
});
links.push({
source: src,
target: tgt,
paytime: PayTime[i],
patogeno: TXN_COUNT[i], // cambio ---- variable con cual trabajar
total_amt: Total_Amt[i],
SendTime: SendTime[i],
value: 1
});
});
I need to know the value of every patogeno and return it to compare it. Is there a way to do it?, or How to return a specific value, for example: "patogenoB" from IDData?

First, JSON.stringify produces a string.
const obj = {example: 5}
const str = JSON.stringify(obj)
console.log(typeof str) // 'string'
If you want an addressable object, you would do the reverse to a string:
const str = '{"example": 5}'
const obj = JSON.parse(str)
console.log(obj.example) // 5
I do not know how to answer your question with respect to JSON.stringify, nor do I understand why you would be turning an array of arrays into a string instead of converting them into addressable objects, but at the very end of createNodes, you would be able to do this:
links.forEach((d) => console.log(d.patogeno))

Related

Error while saving JSON data to Firestore collection using cloud function

I am trying to insert array in my firebase collection from cloud function. I need to have multiple lines in one document so for each line i am inserting an array. Please check my attached screenshot where you can see line0 , same way i need to have Line1,Line2,Line3..,Line n in the same document.
for line0 i am passing array from code like below and its working fine.
admin.firestore().collection("qbContestWinners").add(
{
'cmpientryid': context.params.processId,
'qbid': '',
'qbsyncdate': '',
'qbsyncstatus': 'pending',
'Line0':
{
id: "0",
description: 'PRIZE AMOUNT',
amount: 1000,
accountrefid: contestresultData.qbcontestid,
accountrefname: contestresultData.qbcontestname,
contestresultId: context.params.processId,
},
})
when i am looping through data i am getting from another table , i am not able to generate proper JSON to insert.
below is how i am looping and creating JSON after getting data from another table.
i = 1;
admin.firestore().collection("results").where('cid', '==', 'LKRRk2XXXXXXXX')
.orderBy("rank", "asc").get().then(snapshots =>
{
snapshots.forEach(doc =>
{
const contestresultId = doc.id;
const prizeAmount = doc.data().prizeamt;
const userId = doc.data().userid;
const lineNum = "Line" + i;
console.log("new line numner is: ", lineNum);
console.log(`lineNum? ${lineNum}`);
const linetxt = "Line" + String(i);
const insertData = "{"+linetxt +
":{id:'" + i +
"', description: 'PRIZE AMOUNT'"+
", amount:" + prizeAmount + "," +
"accountrefid:"+ contestresultData.qbcontestid +","+
"accountrefname:'" +contestresultData.qbcontestname +"',"+
"contestresultId:'" + contestresultId +"'," +
"},}"
const finalInsert = JSON.stringify(insertData);
const finalJSON = JSON.parse(finalInsert);
admin.firestore().collection("qbContestWinners").doc(mainID).set(
finalInsert.toJSON(),
{
merge: true
});
i= i+1;
});
});
using this code i am getting error
finalInsert.toJSON is not a function
Actually, the Line0 field is a map and not an Array, see this doc for more details.
So, if you want to create similar fields (Line1, Line2, ...), you simply need to pass a JavaScript Object to the set() method, as follows:
snapshots.forEach(doc => {
const contestresultId = doc.id;
const prizeAmount = doc.data().prizeamt;
const userId = doc.data().userid;
const lineNum = "Line" + i;
console.log("new line numner is: ", lineNum);
console.log(`lineNum? ${lineNum}`);
const lineObj = {
id: i,
description: 'PRIZE AMOUNT',
accountrefid: contestresultData.qbcontestid, //Not sure if you have defined contestresultData somewhere...
//...
}
const dataObj = {};
dataObj["Line" + i] = lineObj // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
admin.firestore().collection("qbContestWinners").doc(mainID).set(dataObj, {merge: true});
i= i+1;
});
HOWEVER, note that you must return a promise that resolves when all the asynchronous work in your Cloud Function is complete (i.e. call to the Firestore set() method).
This is explained in the official Firebase video series, watch in particular the three videos titled "Learn JavaScript Promises".
Since you are calling several times the set() method in a forEach loop, you need to use Promise.all() in order to return a Promise when all these parallel calls to the set() method are completed.
The following should do the trick:
let i = 1;
return admin.firestore().collection("results") // <-- See the return here
.where('cid', '==', 'LKRRk2XXXXXXXX')
.orderBy("rank", "asc").get()
.then(snapshots => {
const promises = [];
snapshots.forEach(doc => {
const contestresultId = doc.id;
const prizeAmount = doc.data().prizeamt;
const userId = doc.data().userid;
const lineNum = "Line" + i;
const lineObj = {
id: i,
description: 'PRIZE AMOUNT',
accountrefid: contestresultData.qbcontestid,
//...
}
const dataObj = {};
dataObj[lineNum] = lineObj;
promises.push(admin.firestore().collection("qbContestWinners").doc(mainID).set(dataObj, {merge: true}));
i= i+1;
});
return Promise.all(promises) // <-- See the return here
});
A last remark: if mainID keeps the same value in the snapshots.forEach loop, you may adopt a totally different approach, consisting in building a JavaScript object with several LineXX properties and call the set() method only once. Since you didn't share the entire code of your Cloud Function it is impossible to say if this approach should be used or not.
first to the error
You stringify and parse a string. The problem here seems to be the order. You have to parse a "String" and to stringify an "Object". The result won't have a toJSON Method as well, but u can just stringify the Object to get a json.
the second thing
Why do you use a string to create your object? You shouldn't. Just use an object.
the third thing
You should not use Objects as Arrays. Not even in firebase.
Just use arrays. Example:
[Line0Object, Line1Object, ...]
Hint: If your array can work as its own collection. Just use a SubCollection. This might fit your needs.

adding elements to json string(array) FLUTTER

I have a JSON string, inside of it I have an array, I want to add data to it as I tried to do it below:
String myJSON = '{"listOfSubtasks":["dasd","dadd","dadsd"]}';
arrayToStringAndBack(addElement) async {
var json = jsonDecode(myJSON);
var getArray = json['listOfSubtasks']; //returns [dasd,dadd,dadsd]
setState(() {
getArray.add(addElement);
});
// as I want to push it to a db I convert [dasd,dadd,dadsd] to a String ["dasd","dadd","dadsd"]
String arrayToString = jsonEncode(getArray);
print(arrayToString);
}
...
textfieldform
- onSaved: (val) {
subtasks = val;
arrayToStringAndBack(val);
},
...
When I type smth and click on a submit button an element is added to the end of an array but once I try to do it one more time, to add an element, the last element that was added changes to one I created.
I want to add as many elements as I want, not just a single one
Solved
var arrayOfSubTasks = [];
arrayToStringAndBack(addElement, arr) async {
var json = jsonDecode(myJSON);
var getArray = json['listOfSubtasks'];
setState(() {
getArray.add(arr);
});
String arrayToString = jsonEncode(getArray);
print(arrayToString);
}
...
onSaved: (val) {
subtasks = val;
setState(() {
arrayOfSubTasks.add(val);
});
arrayToStringAndBack(val, arrayOfSubTasks);
},
You can treat your list of subtasks as a List to be able to add String with List.add(). Then encode the List to a json with jsonEncode()

Getting access to the keys of an array of objects in es6

i'm new to es6 and i have an array of objects like below:
checkProps = [ {symbol: rwerwe}, {side: Buy}, {status: Hey} ]
With a for loop i want to create a string like:
myurl = localhost:3000/symbol=rwerwe&side=Buy&status=Hey
For this i have to get access to the keys of each object and use concat for the string composition. I used Object.keys but it returns integers. I want something to return the symbol, side and status. How to do this?
Please try this:
var checkProps = [ {symbol: 'rwerwe'}, {side: 'Buy'}, {status: 'Hey'} ];
var urlStr = 'localhost:3000/';
var urlParams = [];
checkProps.forEach(function(o) {
var keys = Object.keys(o);
keys.map(function(key) {
urlParams.push(key + '=' + o[key])
});
});
urlStr += urlParams.join('&');
console.log(urlStr)
You need to loop over the array and apply Object.keys to the items.
const parameters = checkProps.map(item => Object.keys(item).map(key => key + "=" + item[key])[0])
.join("&");
const myUrl = `localhost:3000/${parameters}`;
It's a bit cleaner with ES2017 and Object.entries:
const parameters = checkProps.map(item => Object.entries(item)[0])
.map(parameter => parameter.join("="))
.join("&");

Get element with max value from an object in Angular

Couldn't find anything about this.
I have this controller:
app.controller('StatsCtrl', function ($scope, $http) {
$http.get('stats.json').success(function(data) {
$scope.stats = data;
});
});
The stats.json has:
{"lang":{"en":28,"und":1,"ja":9,"es":14,"ru":1,"in":1,"ko":1,"th":1,"ar":1}}
What I need is to assign the maximum value from the lang object to $scope.max in the controller. What is the best way to do this?
https://jsfiddle.net/kaiser07/6h317Lvv/
var jsonText = '{"lang":{"en":28,"und":1,"ja":9,"es":14,"ru":1,"in":1,"ko":1,"th":1,"ar":1}}';
var data = JSON.parse(jsonText).lang
var maxProp = null
var maxValue = -1
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var value = data[prop]
if (value > maxValue) {
maxProp = prop
maxValue = value
}
}
}
You can do it with a couple of native methods:
$scope.max = Math.max.apply(null, Object.keys(data.lang).map(function(key) {
return data.lang[key];
}));
I would suggest to use underscore.js _.max:
_.max(list, [iteratee], [context])
Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required.
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name: 'curly', age: 60};
link

Defining a Mongoose schema from a JSON file

I want to define my mongoose schema from JSON file. This is my JSON file structure:
{
"default": [
{
"item": "productTitle",
"label": "Product Title",
"note": "e.g Samsung GALAXY Note 4",
"type": "text",
"required": "Product Name cannot be blank..."
},
{
"item": "productCode",
"label": "Product Code",
"type": "text",
"required": "Product Code cannot be blank..."
}
]}
This is my node.js model:
// Load the module dependencies
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var fs = require('fs');
var file = __dirname + '/product.server.model.json';
// Read the json file
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
productJson[data.default[i].slug] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
});
// Define a new 'ProductSchema'
var ProductSchema = new Schema(
// Here I want to put JSON Data 'productJson'
);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
I tried every possible way to define mongoose schema from JSON data 'productJson'. But unless I pre-define my mongoose schema, it is not working. Is there any way to define mongoose schema from JSON data in my model? Any suggestion please?
fs.readFile is an asynchronous function which means that it returns immediately and then later provides its results to the caller via the callback function that you provide as the third parameter.
As such, you need to hold off on using productJson until its populated within that callback. That means moving your schema and model creation inside the callback as well.
fs.readFile(file, 'utf8', function (err, data) {
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
});
Another alternative you can use here is to use the synchronous fs.readFileSync method to read the file instead. This is helpful in startup/initialization cases like this where your application as a whole shouldn't proceed until this file is processed.
var data = fs.readFileSync(file, 'utf8');
data = JSON.parse(data);
var productJson = {};
for(var i = 0; i < data.default.length; i++) {
// Changed .slug to .item here as I don't see slug in the JSON
productJson[data.default[i].item] = {
type: 'String',
required: data.default[i].required,
default: '',
trim: true
}
}
// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);
// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);