Retrieving name of object in firebase - javascript

I have a list / an array of objects organized numerically which i consider the object name as an 'id'. I am using firebase and I can't figure out how to grab the id number itself. Any help would be great
//js
myFirebaseRef.once("value", function(snapshot) {
var list = snapshot.val();
$scope.items = list
console.log($scope.items)
})
//log $scope.items
[1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object, 7: Object //...

with angular.forEach like that you can do something near :
angular.forEach($scope.items,function(key,value){
//the key will contain your id
console.log(key);
})

Is this what you're looking for?
myFirebaseRef.once("value", function(snapshot) {
//var list = snapshot.val();
snapshot.forEach(function(itemSnapshot) {
console.log(itemSnapshot.key); // if you're using 2.x that is key()
});
})

Like this. You use obj[key] = value; to set the id with a variable.
function update(node,key,value){
var ref = firebase.database().ref('/');
var obj = {};
obj[key] = value;
ref.child(node).update(obj)
.then(function() {
console.log('Update Ran Successfully');
});
}

This is a real live example, using react and axios to retrieving the name of the object in firebase :
componentDidMount() {
axios.get('/uri.json')
.then(res => {
let fetchedData = [];
for (let key in res.data) {
fetchedData.push({
...res.data[key],
id: key //The key here holds the object's name !
});
}
});
}

Related

Size of object array is being added to the localstorage not the array of objects

useEffect(() => {
const arr = {
i: id,
quant: quantity,
};
if (localStorage.hasOwnProperty('quantityData') === true) {**checking if the local storage has the 'quantityData' property already**
if (JSON.parse(localStorage.getItem('quantityData').length !== 0)) {
const getData = JSON.parse(localStorage.getItem('quantityData'));
console.log(getData);
const val = getData.find(x => x.i === id);**checking if array has the object with particular id property**
if (val) {**if yes then I will update the quant property of that object with current quantity(state variable)**
getData.forEach(x => {
if (x.i === id) {
x.quant = quantity;
localStorage.setItem('quantityData', JSON.stringify(getData));
}
});
} else {
localStorage.setItem(
'quantityData',
JSON.stringify(getData.push(arr))**If I dont find the element then I will just push the new element in the quantity Data array
);
}
}
} else {
const a = [];
a.push(arr);
localStorage.setItem('quantityData', JSON.stringify(a));**Here when I am uploading the array to the local storage I am getting the size of array in the local storage instaed of the object array**
}
}, [quantity]);
When I am Uploading the data to the localStorage I am getting the size of object array that I have created instead of the array with data object
Javascript array function push returns the new length of the array. You need to push and setItem like belows.
getData.push(arr)
localStorage.setItem(
'quantityData',
JSON.stringify(getData)
);
If you make your const a an object instead of an array it should return properly

Pass array values as parameter to function and create json data

I have a scenario where I am passing an array of objects to a function in nodejs, but the same is failing with undefined error.
Here is what I have tried :
var object = issues.issues //json data
var outarr=[];
for(var key in object){
outarr.push(object[key].key)
}
console.log(outarr) // array is formed like this : ['a','b','c','d','e']
for(var i =0; i<outarr.length;i++){
jira.findIssue(outarr[i]) //here I am trying to pass the array objects into the loop one by one
.then(function(issue) {
var issue_number = issue.key
var ape = issue.fields.customfield_11442[0].value
var description = issue.fields.summary
var ice = issue.fields.customfield_15890[0].value
var vice = issue.fields.customfield_15891.value
var sor = issue.fields.labels
if (sor.indexOf("testcng") > -1) {
var val = 'yes'
} else {
var val = 'yes'
}
var obj = {};
obj['ape_n'] = ape;
obj['description_n'] = description;
obj['ice_n'] = ice;
obj['vice_n'] = vice;
obj['sor_n'] = val;
var out = {}
var key = item;
out[key] = [];
out[key].push(obj);
console.log(out)
} })
.catch(function(err) {
console.error(err);
});
});
What I am trying to achieve : I want to pass the array values as a parameter which is required by jira.findissue(bassically passing the issue number) one by one and which should again fetch the values and give a combine json output.
How can I pass this array values one by one in this function and also run jira.findissue in loop.
Any help will be great !! :-)
I have taken a look at the code in your question.
To be honest the code you wrote is messy and contains some simple syntax errors.
A good tip is to use a linter to avoid those mistakes.
More info about linters here: https://www.codereadability.com/what-are-javascript-linters/
To output all results in one array you have to define the array outside the scope of the loop.
I cleaned the code a bit up and use some es6 features. I don't know the context of the code but this is what I can make off it:
//map every value the key to outarr
let outarr = issues.issues.map( elm => elm.key);
//Output defined outside the scope of the loop
let output = [];
//looping outarr
outarr.forEach( el => {
jira.findIssue(el).then(issue => {
//creating the issue object
let obj = {
ape_n: issue.fields.customfield_11442[0].value,
description_n: issue.fields.summary,
ice_n: issue.fields.customfield_15890[0].value,
vice_n: issue.fields.customfield_15891.value,
sor_n: issue.fields.labels.indexOf("testcng") > -1 ? "yes" : "yes",
};
//pushing to the output
output[issue.key] = obj;
}).catch(err => {
console.log(err);
});
});
//ouputing the output
console.log(output);
Some more info about es6 features: https://webapplog.com/es6/

firebase nested objects returning null - javascript

I want to get the nested child objects like in the images but it is returning null. I want values of price and quantity and show them in table.
Check this database image
here.
Code
var countRef = firebase.database().ref('Orders/' + listid);
countRef.on('value', snapshot => {
var b = snapshot.child("price").val();
var c = snapshot.child("quantity").val();
console.log(c);
});
You are pointing to the wrong path that's why you are getting null. Here is what the Firebase docs say:
If there is no data, the snapshot returned is null.
I can't see your entire database structure from the image but try to double check the path and here is my best guess:
var foodItems = firebase.database().ref(`Orders/'${listid}/foodItems`)
foodItems.on('value', snapshot => {
// the snapshot should return the foodItems array
snapshot.forEach((obj) => {
console.log(obj.price)
console.log(obj.quantity)
})
})
If your listid is and exist key, then you mistyped the path: fooditems so try this;
var countRef = firebase.database().ref('Orders/' + listid);
countRef.on('value', snapshot => {
if (snapshot.exists()) {
var b = snapshot.child("fooditems/price").val();
var c = snapshot.child("fooditems/quantity").val();
console.log(c);
}
});

How to get only one element from an array (firebase database, nodejs)

If I use limitToLast(1), then I still get an object, with one key-value pair. To get the value, I use this code:
db.ref('/myarray').limitToLast(1).once('value').then(function(snapshot) {
var result = snapshot.val();
var lastElem;
var lastKey;
for(var i in result) {
lastElem= result[i];
lastKey = i;
break;
}
...
});
It works, but I think I do it wrong. But haven't found any better solution in the docs. How should I load only one element?
The database looks like this:
When using Firebase queries to get children, use the "child_added" event:
db.ref("/myarray")
.orderByKey() // order by chlidren's keys
.limitToLast(1) // only get the last child
.once("child_added", function(snapshot) {
var key = snapshot.key;
var val = snapshot.val();
...
});

Google Firebase OrderByChild is not working with nested dynamic keys

Order by child (name) is not working when dynamic keys comes between actual reference and data.
Here is my code:
firebase.database().ref('/usersProfile').orderByChild('name').on('value', function(snapshot) {
callback(snapshot);
});
callback(snapshot) {
//console.log(snapshot);
let data = snapshot.val();
self.users = [];
for(let key in data) {
let value = data[key];
value.categId = key;
self.users.push(value);
}
}
And here is my data collected over server:
I think your forward slash might be the problem. It should probably look something like this:
firebase.database().ref().child("usersProfile").orderByChild("name").on("value", function(snapshot) {
callback(snapshot);
});

Categories

Resources