i want to iterate over an array, however my array is an observer. i have tried several ways, like converting to an array. nothing works.
does anyone have a suggested solution?
i'm pretty stuck on this.
here is my code:
var vm = new Vue({
el: '#app',
data() {
return {
segmenteConfig: []
}
},
methods: {
async loadData(type) {
var url = null;
console.log("used configs -> ", this.segmenteConfig);
this.segmenteConfig.forEach(segmenteConfig => {
if (segmenteConfig.type === type) {
url = segmenteConfig.url;
console.log("used configs url -> ", url);
}
})
}
loadConfig() {
var config = [];
axios.get("ressources/segmente.json")
.then(response => {
response.data.Segmente.forEach(segmentConfig => {
this.segmenteConfig.push(segmentConfig);
});
});
}
},
created() {
this.loadConfig();
this.loadData('internet');
}
});
Related
All things are going right, when I try to log array it writes everything true but when I try to return as response, it goes empty to front-end. I'm not sure why this is happening, the normal messages array works fine. I don't know why.
console.log('messageye girdi');
MessageModel.find({
receiver: req.body.uuid,
read: false
}).then((Messages) => {
function removeDups(names) {
let unique = {};
names.forEach(function(i) {
if (!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
let Users = [];
Messages.forEach(Message => {
Users.push(Message.sender);
})
const nonduplicate = removeDups(Users);
console.log(nonduplicate);
const MessageUsers = [];
var bu = 0;
nonduplicate.forEach(User => {
UserModel.findOne({
uuid: User
}).then((UserData) => {
console.log(UserData.username);
MessageUsers.push(UserData.username);
console.log(MessageUsers);
})
bu++;
if (bu = nonduplicate.length) {
console.log("bu mu acaba " + JSON.stringify(MessageUsers));
let ArrayVer = Object.assign({}, MessageUsers);
return res.send({
success: true,
users: MessageUsers
});
}
});
I am trying to append the new object in the for loop to the request JSON.
this is not working :
setCapabilities('default',['1','2','3'])
export function
setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj = {
element:true
}
console.log(obj)
});
}
This is also not working :
export function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]){
var request:object = {
type:'setCapabilities',
kaiId:kaiId
};
capabilitiesArr.forEach(element => {
var obj[element]=true
console.log(obj)
});
}
I want the output to be as :
console.log(request)
{
type:'setCapabilities',
kaiId:'default',
'1':true,
'2':true,
'3':true
}
I've updated the code in javascript for browser to run the code snippet, but you can convert it to typescript for your use
function setCapabilities(kaiId, capabilitiesArr) {
var request = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = Object.assign({}, request)
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
setCapabilities('default',['1','2','3'])
In typescript use below code
function setCapabilities(kaiId:number|"default"|"defaultLeft"|"defaultRight",capabilitiesArr:string[]) {
var request:object = {
type: 'setCapabilities',
kaiId: kaiId
}
var obj = {...request}
capabilitiesArr.forEach(element => {
obj[element] = true
});
console.log(obj)
}
I want to compare the data which I got from Mongo to javascript array. I am using lodash to compare. But it always return incorrect result.
var editUser = function(userData, getOutFunction) {
var status = CONSTANTS.NG;
checkExistUser(userData._id).then(function(user) {
if (user !== null) {
var userGroup = JSON.stringify(user.group);
user.group = user.group.map((groupId) => {
return groupId.toString();
});
var removedGroups = _.difference(userGroup, userData.group);
var addedGroups = _.difference(userData.group, userGroup);
console.log('Removed Groups: ', removedGroups);
console.log('Added Groups: ', addedGroups);
} else {
status = CONSTANTS.NG;
logger.debug(DEBUG_CLASS_NAME, "Cannot find object");
if (typeof(getOutFunction) !== 'undefined') {
getOutFunction(status, null);
} else {
NO_CALLBACK();
}
}
}).catch(function() {
console.log('Promise is error');
});
var checkExistUser = function(userId) {
return new Promise(function(resolve, reject) {
UserDAO.findById(userId, function(err, user) {
if (err) {
logger.debug(DEBUG_CLASS_NAME, {
name: err.name,
code: err.code,
message: err.message,
method: "checkExist"
});
resolve(null);
} else {
resolve(user);
}
});
});
}
For example:When I try to input value for lodash difference function
var user.group = ["58b8da67d585113517fed34e","58b8da6ed585113517fed34f"];
var userData.group = [ '58b8da67d585113517fed34e' ];
I want lodash difference return below result:
Removed Groups: ['58b8da6ed585113517fed34f']
Added Groups: []
However, the function gave me the result like:
Removed Groups: []
Added Groups: [ '58b8da67d585113517fed34e' ]
Can anyone help me in this case?
I will do appreciate it.
I have had this issue as well, the result from mongodb is an ObjectId type so you can compare the someObjectId.toString() value with your array of strings, or you could use
someObjectId.equals(stringOrObjectIdValue)
However, if you want to keep using lodash functions you will either have to force both arrays to strings or to ObjectIds before passing them into the function.
See my code below.
exports.myexports = (req, res) => {
var arrayname = new Array();
Hello.find({},function(error,fetchAllHellos)
{
if(fetchAllHellos)
{
async.eachSeries(fetchAllHellos, function(Hello, callback)
{
var hArr = {};
var image = {};
hArr['_id'] = Hello._id;
hArr['myname'] = Hello.name;
/* Use asyn Parallel method for waiting those functions value */
async.parallel
(
[
function(callback)
{
fetchingDetails(Hello._id, function(err, fetchAllDetails)
{
bArr['address'] = fetchAllDetails;
async.eachSeries(fetchAllDetails, function(fetchAllDetails, callback)
{
async.parallel
(
[
function(callback)
{
fetchingMyImage(fetchAllDetails._id, function(err, wer)
{
image[fetchAllDetails._id] = wer;
callback(err); //Forgot to add
})
}
],
function(err)
{
//console.log(image);
arrayname.push(image);
//bArr['image'] = image
callback(err);
}
);
});
callback(err); //Forgot to add
});
}
],
function(err)
{
arrayname.push(hArr);
callback(err);
}
)
},
function(err)
{
console.log(arrayname); //This should give you desired result
});
}
else
{
return res.json({"status":'error'})
}
});
};
function fetchingMyImage(mid, callback)
{
UserImage.find({myid:mid},function(error,fetchallImages)
{
callback(error,fetchallImages);
});
}
I want like this array
user
[
id = 'lkjlk',
myname = 'helloname'
address = [
object,
]
image = [
myid = image.png
]
]
Made changes in your code. Let me know if it helps you.
Please go through the code and let me know, whether you understood the changes or not.
exports.myexports = (req, res) => {
var arrayname = new Array();
Hello.find({},function(error,fetchAllHellos)
{
if(fetchAllHellos)
{
async.eachSeries(fetchAllHellos, function(Hello, callback)
{
var hArr = {};
var image = [];
hArr['_id'] = Hello._id;
hArr['myname'] = Hello.name;
//Read doc before you can start using.
async.parallel
([
function(callback)
{
fetchingDetails(Hello._id, function(err, fetchAllDetails)
{
bArr['address'] = fetchAllDetails;
async.eachSeries(fetchAllDetails, function(eachDetail, callback)
{
fetchingMyImage(eachDetail._id, function(err, wer)
{
image.push({eachDetail._id : wer;
callback(err);
})
}, function(err)
{
console.log(image);
arrayname.push({images :image});
callback(err);
});
});
}
],
function(err)
{
arrayname.push(hArr);
callback(err);
})
},
function(err)
{
console.log(arrayname); //This should give you desired result
console.log(arrayname.images)// Array of images will be consoled here.
//callback(err);
});
}
else
{
return res.json({"status":'error'})
}
});
};
function fetchingMyImage(mid, callback)
{
UserImage.find({myid:mid},function(error,fetchallImages)
{
callback(error,fetchallImages);
});
}
I'm trying to learn firebase/angularjs by extending an app to use firebase as the backend.
My forge looks like this
.
In my program I have binded firebaseio.com/projects to $scope.projects.
How do I access the children?
Why doesn't $scope.projects.getIndex() return the keys to the children?
I know the items are in $scope.projects because I can see them if I do console.log($scope.projects)
app.js
angular.module('todo', ['ionic', 'firebase'])
/**
* The Projects factory handles saving and loading projects
* from localStorage, and also lets us save and load the
* last active project index.
*/
.factory('Projects', function() {
return {
all: function () {
var projectString = window.localStorage['projects'];
if(projectString) {
return angular.fromJson(projectString);
}
return [];
},
// just saves all the projects everytime
save: function(projects) {
window.localStorage['projects'] = angular.toJson(projects);
},
newProject: function(projectTitle) {
// Add a new project
return {
title: projectTitle,
tasks: []
};
},
getLastActiveIndex: function () {
return parseInt(window.localStorage['lastActiveProject']) || 0;
},
setLastActiveIndex: function (index) {
window.localStorage['lastActiveProject'] = index;
}
}
})
.controller('TodoCtrl', function($scope, $timeout, $ionicModal, Projects, $firebase) {
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
var keys = $scope.projects.$getIndex();
console.log($scope.projects.$child('-JGTmBu4aeToOSGmgCo1'));
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("" + keys[0]);
});
// A utility function for creating a new project
// with the given projectTitle
var createProject = function(projectTitle) {
var newProject = Projects.newProject(projectTitle);
$scope.projects.$add(newProject);
Projects.save($scope.projects);
$scope.selectProject(newProject, $scope.projects.length-1);
};
// Called to create a new project
$scope.newProject = function() {
var projectTitle = prompt('Project name');
if(projectTitle) {
createProject(projectTitle);
}
};
// Called to select the given project
$scope.selectProject = function(project, index) {
$scope.activeProject = project;
Projects.setLastActiveIndex(index);
$scope.sideMenuController.close();
};
// Create our modal
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope
});
$scope.createTask = function(task) {
if(!$scope.activeProject || !task) {
return;
}
console.log($scope.activeProject.task);
$scope.activeProject.task.$add({
title: task.title
});
$scope.taskModal.hide();
// Inefficient, but save all the projects
Projects.save($scope.projects);
task.title = "";
};
$scope.newTask = function() {
$scope.taskModal.show();
};
$scope.closeNewTask = function() {
$scope.taskModal.hide();
};
$scope.toggleProjects = function() {
$scope.sideMenuController.toggleLeft();
};
// Try to create the first project, make sure to defer
// this by using $timeout so everything is initialized
// properly
$timeout(function() {
if($scope.projects.length == 0) {
while(true) {
var projectTitle = prompt('Your first project title:');
if(projectTitle) {
createProject(projectTitle);
break;
}
}
}
});
});
I'm interested in the objects at the bottom
console.log($scope.projects)
Update
After digging around it seems I may be accessing the data incorrectly. https://www.firebase.com/docs/reading-data.html
Here's my new approach
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
console.log(snapshot.val()['-JGTdgGAfq7dqBpSk2ls']);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
I'm still not sure how to traverse the keys programmatically but I feel I'm getting close
It's an object containing more objects, loop it with for in:
for (var key in $scope.projects) {
if ($scope.projects.hasOwnProperty(key)) {
console.log("The key is: " + key);
console.log("The value is: " + $scope.projects[key]);
}
}
ok so val() returns an object. In order to traverse all the children of projects I do
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
var keys = Object.keys(snapshot.val());
console.log(snapshot.val()[keys[0]]);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
Note the var keys = Object.keys() gets all the keys at firebaseio.com/projects then you can get the first child by doing snapshot.val()[keys[0])