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("&");
Related
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.
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))
const dataParams = [];
let data={
A:'5',
B:'6',
C:'7',
D:'8'
}
for(let d in data){
dataParams.push(d + '=' + data[d]);
}
console.log(dataParams)
I have an object as below i just need to print it as an array like
["A=5", "B=6", "C=7", "D=8"]
The Below code is working please see the console.
But i have read about the keys and values method in JS
Object.keys(data) // [A,B,C,D]
Object.values(data) // ['5','6','7','8']
Is there any way that i can get the same output with the help of using keys and values method
Use object#entries with array#map
let data={A:'5',B:'6',C:'7', D:'8'},
result = Object.entries(data).map(([key, value]) => `${key}=${value}`);
console.log(result);
You can also use Object.keys()
let data={A:'5',B:'6',C:'7', D:'8'},
result = Object.keys(data).map(k => `${k}=${data[k]}`);
console.log(result);
You can use reduce with Object.keys
var data = {
a:1,
b:2,
c:3,
d:4
}
var list = Object.keys(data).reduce(function(keyValueList, prop){
keyValueList.push(prop + '=' + data[prop])
return keyValueList;
}, []);
console.log(list);
As you're using both key and value, Object.entries is probably best for you:
const dataParams = Object.entries(data).map(([key, value]) => `${key}=${value}`);
I've a data structure like this (generated by normalizr):
const data = fromJS({
templates: {
"83E51B08-5F55-4FA2-A2A0-99744AE7AAD3":
{"uuid": "83E51B08-5F55-4FA2-A2A0-99744AE7AAD3", test: "bla"},
"F16FB07B-EF7C-440C-9C21-F331FCA93439":
{"uuid": "F16FB07B-EF7C-440C-9C21-F331FCA93439", test: "bla"}
}
})
Now I try to figure out how to replace the UUIDs in both the key and the value of the template entries. Basically how can I archive the following output:
const data = fromJS({
templates: {
"DBB0B4B0-565A-4066-88D3-3284803E0FD2":
{"uuid": "DBB0B4B0-565A-4066-88D3-3284803E0FD2", test: "bla"},
"D44FA349-048E-4006-A545-DBF49B1FA5AF":
{"uuid": "D44FA349-048E-4006-A545-DBF49B1FA5AF", test: "bla"}
}
})
A good candidate seems to me the .mapEntries() method, but I'm struggling on how to use it ...
// this don't work ... :-(
const result = data.mapEntries((k, v) => {
const newUUID = uuid.v4()
return (newUUID, v.set('uuid', newUUID))
})
Maybe someone can give me a hand here?
mapEntries is the correct method. From the documentation, the mapping function has the following signature:
mapper: (entry: [K, V], index: number, iter: this) => [KM, VM]
This means that the first argument is the entry passed in as an array of [key, value]. Similarly, the return value of the mapper function should be an array of the new key and the new value. So your mapper function needs to look like this:
([k, v]) => {
const newUUID = uuid.v4()
return [newUUID, v.set('uuid', newUUID)]
}
This is equivalent to the following (more explicit) function:
(entry) => {
const key = entry[0]; // note that key isn't actually used, so this isn't necessary
const value = entry[1];
const newUUID = uuid.v4()
return [newUUID, value.set('uuid', newUUID)]
}
One thing to note is that the templates are nested under the templates property, so you can't map data directly -- instead you'll want to use the update function.
data.update('templates', templates => template.mapEntries(...)))
So putting everything together, your solution should look like the following:
const result = data.update('templates', templates =>
templates.mapEntries(([k, v]) => {
const newUUID = uuid.v4()
return [newUUID, v.set('uuid', newUUID)]
})
);
OK, we all know this works:
vm.myObject = {
required : "This field requires data",
.....
}
But how can I create that same object dynamically when the property 'keys' and 'values' come from a json file, eg:
json:
[
{ "key" :"required", "value": "This field requires data"},
.....
]
service:
var myObject = {}
DynamicObjSvc.get()
.success(function(data){
data.forEach(function(item){
// pass each key as an object property
// and pass its respective value
?????????
})
.....
UPDATE:
Kavemen was mostly correct, this turned out to be the solution:
var myObject = {};
DynamicObjSvc.all()
.success(function(data){
angular.forEach(data, function(msg) {
myObject[msg.key] = msg.value; <-- his answer was incorrect here
});
$fgConfigProviderRef.validation.message(myObject);
})
.error(function(err){
console.log(err.message);
})
You can use angular.forEach and the bracket notation for setting (and getting) object properties in Javascript
var myObject = {}
DynamicObjSvc.get().success(
function(data) {
angular.forEach(data, function(value, key) {
myObject[key] = value;
});
}
);
See also Working with Objects from MDN
EDIT
I see now that your data is really an array of objects, not just a single object, so yes, the code above could lead you astray.
In any case, the method of setting an object's properties dynamically using the bracket notation is sound; the loop could be reworked to handle your data array as such:
//we have an array of objects now
var myObjects = [];
DynamicObjSvc.get().success(
function(data) {
//for each object in the data array
for(var i = 0; i < data.length; i++) {
//create and populate a new object for the ith data element
var newObject = {};
angular.forEach(data[i], function(value, key) {
newObject[key] = value;
});
//and add it to the overall collection
myObjects.push(newObject);
}
}
);