Array of Arrays in JavaScript. Replacement for querySnapshot.forEach - javascript

so I got this.
const querySnapshot = await getDocs(collectionRef);
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
It outputs the following.
0 => Object
1 => Object
2 => Object
I want an array of arrays. Just like this.
[[0],
[1],
[2]]
Please help

Well you can create and external array and push you values in there like so:
const array = [];
const querySnapshot = await getDocs(collectionRef);
querySnapshot.forEach((doc) => {
array.push([doc.id])
});
console.log(array); // [[0],[1],[2]]

If you reach into docs of the snapshot, you get an array and can use all array operations, such as map:
const arr = querySnapshot.docs.map((doc) => [doc.id]);
console.log(arr);

Related

Get documents name in Firestore and create nested object

This question is related to this one: Get documents names in Firestore but I can't comment yet.
I am trying to get a nested object from my FireStore which looks like this
{"docname1": {…}, "docname2": {…}, "docname3": {…}}
I have this now but cant seem to figure out how to create the nested object to push it into the empty array.
useEffect(() => {
const getPlants = async () => {
let response = []
const querySnapshot = await firebase
.firestore()
.collection('plants')
.get()
querySnapshot.forEach((doc) => {
let newObject = [doc.id: doc.data() ]
response.push(newObject)
})
setPlants(response)
}
getPlants()
}, [])
Any help is greatly appreciated :)
I think you are creating the new object (newObject) wrong. Try to create it like this:
querySnapshot.forEach((doc) => {
const newObject = {}
newObject[doc.id] = doc.data()
response.push(newObject)
})
Or, you can do this:
querySnapshot.forEach((doc) => {
response.push({ [`${doc.id}`]: doc.data() })
})

How do I convert the firestore data to a JSON object?

I have these codes:
const App = () => {
const [users, setUsers] = useState();
const getData = async () => {
const citiesRef = firestore.collection("users");
const snapshot = await citiesRef
.where("item.itemName", "==", true)
.where("item", "==", false)
.get();
if (snapshot.empty) {
console.log("No matching documents.");
return;
}
snapshot.forEach((doc) => {
console.log(doc.data());
});
};
useEffect(() => {
getData();
});
return <div>Month</div>;
};
export default App;
If I'll console.log(doc.data()) this is what is shows:
How can I convert this into a JSON object?
I wanted to have a JSON object in order to filter the data. Thank you.
If you are trying to get an array of objects containing all documents' data to filter them, try this:
const usersData = snapshot.docs.map(d => ({id: d.id, ...d.data()}))
// set this array in your state
setUsers(usersData)
This will be an array and you can use methods like filter(), find() as required. For example, to get users having admin role in their roles array:
const admins = usersData.filter(user => user.roles.includes("admin"))

Loop through an array list to make a post request for a rest API dynamic

I update an object. This object is an array which can have a length from one to five. This is my object ["max", "dog"].
Now a post method is to be called. It is so if the user has only 2 things filled in, only two things should be sent there. If 5 then 5 (see example for a better explanation.) Does anyone have an idea how best to set this up?
const tag = ["max", "dog"]
const updateInterest = () => {
axios
.post("...", {
first1: max,
first2: dog,
// first3: ...,
// first4: ...,
// first4: ...,
})
.then((res) => {
if (res.status === 200) {
// API update interest
}
})
.catch((error) => {
console.log(error);
});
};
What I try
const tag = ["max", "dog"]
const updateInterest = () => {
const object = "";
tags.map((tag, index) =>{
console.log(tag + " " + index)
object =
`first${index}`: `${tag}`,
})
axios
.post("...", {
object
})
.then((res) => {
if (res.status === 200) {
// API update interest
}
})
.catch((error) => {
console.log(error);
});
};
My loop doesn't really make much sense. How can I add this to an object so that it can be sent in later in an API?
You can use Object.fromEntries() to map an array of arrays to object, like in the following example:
const arr = ["max", "dog"];
const mapped = arr.map((el, i) => [`first${i+1}`, el]);
console.log(Object.fromEntries(mapped))
You can also use Array.prototype.reduce() to achieve the same thing:
const arr = ['cat', 'dog'];
const obj = arr.reduce((acc, cur, i) => ((acc[`first${i + 1}`] = cur), acc), {});
console.log(obj);
Reference: Convert Array to Object

from array of objects to an object [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 3 years ago.
I have an array like this:
array = [{profile: 'pippo'}, {profile: 'mickey'}]
and I would like to transform it to this:
object = {0: 'pippo', 1: 'mickey'}
You can use a short reduce:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.reduce((a, o, i) => (a[i] = o.profile, a), {})
console.log(output)
Or even use Object.assign:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = Object.assign({}, array.map(o => o.profile))
console.log(output)
However, your output is in the same format as an array, so you could just use map and access the elements by index (it really just depends on the use case):
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const output = array.map(o => o.profile)
console.log(output)
Extract the profiles value with Array.map() and spread into an object:
const array = [{profile: 'pippo'}, {profile: 'mickey'}]
const result = { ...array.map(o => o.profile) }
console.log(result)
using reduce it would be very easy. there you have how it works and a working example.
array = [{
profile: 'pippo'
}, {
profile: 'mickey'
}]
const finalObj = array.reduce((accum, cv, index) => {
accum[index] = cv['profile']
return accum;
}, {})
console.log(finalObj)

Firebase cloudstore collections map vs. forEach

I am trying to use the map function to create an array of the items returned from a collection.
My implementation is using the forEach to iterate which works fine. However, I can't get it to work with the map function.
Here's the code:
firestore.collection("notes").doc(this.props.id).collection('items').get()
.then((snap) => {
let items = []
snap.forEach((doc) => {
items.push({id:doc.id,text:doc.data().text})
console.log(`${doc.id} => ${doc.data()}`);
});
console.log(items)
});
However, this doesn't work:
firestore.collection("notes").doc(this.props.id).collection('items').get()
.then((snap) => {
let items = snap.map((doc) => {
return {id:doc.id, text:doc.data().text}
})
console.log(items)
});
It shoots an error that 'snap.map' is not a function.
I can't figure out where I'm tripping?
The forEach method exists, but not map.
However you can get an array of docs:
An array of all the documents in the QuerySnapshot.
Which you can call map on, like this:
let items = snap.docs.map(doc => {
return { id: doc.id, text: doc.data().text }
})
snap may not be a true array. It's probably some sort of array-like object. Try creating a new array with the spread operator (...), then working on that, like this:
firestore.collection("notes").doc(this.props.id).collection('items').get()
.then((snap) => {
let items = [...snap].map((doc) => {
return {id:doc.id, text:doc.data().text}
})
console.log(items)
});
That should convert it to a true array which will give you the ability to use the .map function.
A little example, in my case, Im update something:
const query = ...collection("notes").doc(this.props.id).collection('items');
query.snapshotChanges().map(changes => {
changes.map(a => {
const id = a.payload.doc.id;
this.db.collection("notes").doc(this.props.id).collection('items').update({
someItemsProp: newValue,
})
})
}).subscribe();
}

Categories