Working on API response that gets user data from 10K ft system via API. The response looks like:
"data": [{
"id": 30000,
"display_name": "John Doe",
"email": "Johndoes#testmail.com",
},
I want to save this data in three different arrays for each response to be used later for looping through user id. I am not sure how to go about it. Below is the code I have worked on so far. I will appreciate any help here. Thanks
function getUsers() {
var auth = 'authentication'
var url = 'https://api.10000ft.com/api/v1/users?' + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
};
let response = UrlFetchApp.fetch(url, options);
let json = JSON.parse(response);
};
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response);
var ids = [];
var display_names = [];
var emails = [];
function result(data) {
data.forEach(element => {
ids.push(element.id);
display_names.push(element.display_name);
emails.push(element.email);
});
return { "ids": ids, "display-names": display_names, "emails": emails };
}
console.log(result(data));
From what I understand...Maybe you're looking for something like this?
let json = JSON.parse(response);
let ids = [];
let dis_name = [];
let email = [];
for(let i = 0; i < json.length; i++){
ids.push(json[i].id);
dis_name.push(json[i].display_name);
email.push(json[i].email);
}
P.S Consider using let keyword instead of var.
if "data" contains more objects you need to loop through the data array and push the ids, display_names and emails in separate arrays. The below example will help you.
var data = [
{
"id": 30000,
"display_name": "John Doe",
"email": "Johndoes#testmail.com"
},
{
"id": 30001,
"display_name": "John Cena",
"email": "JohnCens#testmail.com"
},
{
"id": 30002,
"display_name": "John kabaraya",
"email": "Johnkabarayas#testmail.com"
}
]
var ids = [];
var display_names = [];
var emails = [];
function result(data) {
data.forEach(element => {
ids.push(element.id);
display_names.push(element.display_name);
emails.push(element.email);
});
return { "ids": ids, "display-names": display_names, "emails": emails };
}
console.log(result(data));
Creating an array based off selected DataTables Rows
$('#savenlp').click(recordjourney);
function recordjourney() {
var data = table.rows(['.selected']).data().toArray();
console.log( (data) );
console.log( JSON.stringify(data) );
}
data returns
0 : (8) ["Which", "TitleCase", "QuestionWord", "", "", "", "", ""]
JSON.stringify(data) returns
[["baseball","Noun","Singular","","","","",""]]
This information is dynamically generated, so I am just looking to take the first value (in this case baseball) and turn it into something like
"baseball": [
"Noun",
"Singular"
]
I can return the first value (the key I want using)
alert(data[0][0]);
I am much more adept in PHP but I am learning javascript/jquery more and more.
It is my understanding javascript does not have associative arrays, so I am a bit confused as to how to generate this.
const data = [
["baseball","Noun","Singular","","","","",""],
["baseballs","Noun","","Plural","","","","",]
];
const mappedData = data.reduce((acc, row) => { acc[row.shift()] = row.filter(d => d !== ''); return acc; }, {});
console.log(mappedData);
We can use object destructuring and spread operators for ease of use.
In the example below, the key will be the first item and all the rest items will be placed in the newData variable
const data = [["baseball","Noun","Singular","","","","",""]];
const [key, ...newData] = data[0]
// if you want the new data to not have empty entries, simple apply the filter
const newDataFiltered = newData.filter(item => !!item)
const objWithEmpty = {[key]: newData}
const objWithoutEmpty = {[key]: newDataFiltered}
console.log(objWithEmpty, objWithoutEmpty)
For multiple arrays inside the outer array, just enclose the whole logic inside a for loop
const data = [
["baseball","Noun","Singular","","","","",""],
["baseball1","Noun1","Singular1","","","","",""],
["baseball2","Noun2","Singular2","","","","",""]
];
const objWithEmpty = {}
const objWithoutEmpty = {}
data.forEach((array) => {
const [key, ...newData] = array
// if you want the new data to not have empty entries, simple apply the filter
const newDataFiltered = newData.filter(item => !!item)
objWithEmpty[key] = newData
objWithoutEmpty[key] = newDataFiltered
})
console.log(objWithEmpty, objWithoutEmpty)
Simply extract the desired values from data and put them into an object formatted as you like:
const data = [["baseball","Noun","Singular","","","","",""]];
const firstArr = data[0];
const transformedFirstObject = {
[firstArr[0]]: [firstArr[1], firstArr[2]],
};
console.log(transformedFirstObject);
But it's pretty weird to have an object with only one property like that. If your data might have more than one sub-array in it and you want to turn the array of arrays into an array of objects, use map:
const data = [
["baseball","Noun","Singular","","","","",""],
["foo","bar","baz","","","","",""]
];
const transformed = Object.assign(...data.map(([prop, value1, value2]) => ({ [prop]: [value1, value2] })));
console.log(transformed);
A bit simpler compared to other answers here but works as well.
const data = [
["baseball","Noun","Singular","","","","",""],
["baseball1","Noun1","Singular1","","","","",""],
["baseball2","Noun2","Singular2","","","","",""]
];
const obj = [];
data.forEach(function(i) {
let jsonObj = {};
jsonObj [i[0]] = i.slice(1).filter(x=>x !='');
obj.push(jsonObj)
});
console.log(JSON.stringify(obj))
Just using forEach, considering multiple array elements.
var obj = {};
var arr = [
["baseball", "Noun", "Singular", "", "", "", "", ""],
["Test", "Test1", "Test2", "", "", "", "", ""]
];
arr.forEach(function(val, idx) {
val.forEach(function(val1, idx1) {
if (idx1 === 0) {
obj[val1] = val.slice(1, val.length)
}
})
})
console.log(JSON.stringify(obj))
I'm querying from firebase realtime database, storing each result in an array, and returning this array. While the data is correct, I am not returning it in a type I want it to be in.
The code for this function is
exports.getprojects = functions.https.onRequest((req, res) => {
const uid = req.body.uid;
var projectref = fref.child('projects');
var projarr = [];
// Make the promise object for query
const projpromise = projectref.orderByChild('key').equalTo(uid).once('value');
// Another Promise for pushing to array
const pushpromise = projpromise.then(snap => {
var proj_item = snap.val();
// push to array
projarr.push(proj_item);
return proj_item;
}).catch(reason => {
console.log(reason)
return res.json(400);
})
// Respond with array
return pushpromise.then((proj_item) => {
return res.json(200, projarr);
}).catch(reason => {
console.log(reason)
return res.json(400);
})
});
This function queries all the right data, but returns in format like this :
[
{
"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
},
...
]
What I need is for this function to return in format like below :
{
{
"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
},
...
}
How can I achieve this? Any help is appreciated. Thank you!
To turn your array into a JSON object with just the key-value pairs, do something like this:
var array = [
{"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
}},
{"project_id2": {
"project_title": "Test Project2",
"project_type": "Medium Term"
}},
{"project_id3": {
"project_title": "Test Project3",
"project_type": "Short Term"
}}
];
var result = {};
array.forEach(function(object) {
var key = Object.keys(object)[0];
result[key] = object[key];
})
console.log(result);
How do I sort the following structure in Firebase by sortOrder?
categories {
{
"b": {
"name": "Banana",
"sortOrder": 2
},
"a": {
"name": "Apple",
"sortOrder": 1
}
}
}
From the documentation it looks as simple as:
ref('categories').orderByChild('sortOrder').once('value') ...
However, the first node returned is banana. It doesn't matter what string value I use. For example, the following returns the same results:
ref('categories').orderByChild('xxx').once('value') ...
Full function:
public list(): Observable<Category[]> {
let ref = firebase.database().ref('categories').orderByChild('sortOrder');
return Observable.fromPromise(<Promise<any>>ref.once('value'))
.flatMap(snapshot => {
let objects = snapshot.val();
let categories: Array<Category> = new Array();
for (let key in objects) {
let category: Category = objects[key];
category.code = key;
categories.push(category);
}
return Observable.of(categories);
}
);
}
The problem is that when you access the children via the snapshot's value's keys, the order is indeterminate.
You need to use the snapshot's forEach method:
return Observable.fromPromise(<Promise<any>>ref.once('value'))
.flatMap(snapshot => {
let categories: Array<Category> = new Array();
snapshot.forEach(childSnapshot => {
let category: Category = childSnapshot.val();
category.code = childSnapshot.key;
categories.push(category);
});
return Observable.of(categories);
}
);
Also, you could just use map and return categories.
My rest API returns with the following json content:
[{
"key": "apple",
"value": "green"
},
{
"key": "banana",
"value": "yellow"
}]
I am iterating through the list with this code:
this.props.json.map(row => {
return <RowRender key={id.row} row={row} />
}
It works because the content is displayed but on the web browser's console I can see an error:
map is not a function
I googled for it and I changed my code to this:
Array.prototype.slice.call(this.props.json).map(row => {
return <RowRender key={id.row} row={row} />
}
It works without any error but seems so complicated. Is that the correct way to do this job?
UPDATE
What I tried:
JSON.parse(...).map: Unexpected end of JSON input
JSON.parse(JSON.stringify(...)).map(...): data is displayed but I get an error: JSON.parse(...).map is not a function
Array(...).map: Each child in array or iterator should have a unique key.
Use Object.entries() to get both the key and values, then give that to Map() to allow you to select your values by key.
let myMap = new Map(Object.entries(this.props.json));
in your code this.props.json is not an array, it's an array-like object and map is an array function. what your doing to solve this, is converting that array-like object into an array, with .slice()
a more elegant way to do this:
Array.from(this.props.json).map(row => <RowRender key={id.row} row={row} />)
let jsonMap = JSON.stringify([...map.entries()])
let myMap = new Map(JSON.parse(jsonMap));
You can do it very easily as #Gary mentioned in his answer:
From Map to JSON (string keys):
const personsJson = `{"1":{"firstName":"Jan","lastName":"Kowalski"},"2":{"firstName":"Justyna","lastName":"Kowalczyk"}}`;
const personsObject = JSON.parse(personsJson);
const personsMap = new Map(Object.entries(personsObject));
for (const key of personsMap.keys()) {
console.log(typeof key)
}
But there is one issue about which you have to be careful. Key of the map created in that way will always be a STRING. It will happen, because KEY of JSON object is always a STRING. So if your Map keys should be numbers then first you have parse keys of your object entries.
From JSON to Map (number keys)::
const personsJson = `{"1":{"firstName":"Jan","lastName":"Kowalski"},"2":{"firstName":"Justyna","lastName":"Kowalczyk"}}`;
const personsObject = JSON.parse(personsJson);
const personObjectEntries = Object.entries(personsObject);
const personObjectEntriesNumberKeys = personObjectEntries.map(person => {
person[0] = parseInt(person[0]);
return person;
});
const personsMap = new Map(personObjectEntriesNumberKeys);
for (const key of personsMap.keys()) {
console.log(typeof key)
}
There is person[0] because under 0 index there is the key of the object
You can copypaste this function: it would take JSON and return a Map of Maps:
It works with this JSON:
{
"data":{
"1":{
"color":"red",
"size":"big"
},
"2":{
"color":"red",
"size":"big"
},
"3":{
"color":"red",
"size":"big"
},
"4":{
"color":"red",
"size":"big"
},
"5":{
"color":"red",
"size":"big"
}
}
}
function jsonToMap(jsonString) {
var jsonObject = JSON.parse(jsonString);
var dataObject = jsonObject.data;
var dataMap = new Map(Object.entries(dataObject));
var resultMap = new Map();
for (const key of dataMap.keys()) {
console.log(key);
var keyMap = new Map(Object.entries(dataMap.get(key)));
resultMap.set(key, keyMap);
}
console.log("done!");
return resultMap;
}