I have this list JSON:
[{
"password" : "ppp",
"function" : 0,
"id" : 1,
"login" : "ness",
"nom" : "nesrine",
"mail" : "nes#gmail",
"tel" : "238555555"
},
{
"password" : "pass",
"function" : 0,
"id" : 2,
"login" : "bilel.troudi",
"nom" : "bilel",
"mail" : "bilel.troudi91#gmail",
"tel" : null
},
{
"password" : "undefined",
"function" : 1,
"id" : 4,
"login" : "undefined",
"nom" : "ahmed",
"mail" : "ahmed#gmail.com",
"tel" : "221474"
},
{
"password" : "khm",
"function" : 0,
"id" : 5,
"login" : "khm",
"nom" : "khmayes",
"mail" : "bke#live.fr",
"tel" : "235684522"
}
]
I want to retrieve the names(nom) of users with angular I recovered this list in a variable in my code.
if you do not want to use angular js then you can use simple jquery too.
var list = [{"password":"ppp","function":0,"id":1,"login":"ness","nom":"nesrine","mail":"nes#gmail","tel":"238555555"},{"password":"pass","function":0,"id":2,"login":"bilel.troudi","nom":"bilel","mail":"bilel.troudi91#gmail","tel":null},{"password":"undefined","function":1,"id":4,"login":"undefined","nom":"ahmed","mail":"ahmed#gmail.com","tel":"221474"},{"password":"khm","function":0,"id":5,"login":"khm","nom":"khmayes","mail":"bke#live.fr","tel":"235684522"}];
var nameList = [];
for(var i=0;i<list.length;i++){
nameList.push(list[i].nom);
}
$scope.list =[{"password":"ppp","function":0,"id":1,"login":"ness","nom":"nesrine","mail":"nes#gmail","tel":"238555555"},{"password":"pass","function":0,"id":2,"login":"bilel.troudi","nom":"bilel","mail":"bilel.troudi91#gmail","tel":null},{"password":"undefined","function":1,"id":4,"login":"undefined","nom":"ahmed","mail":"ahmed#gmail.com","tel":"221474"},{"password":"khm","function":0,"id":5,"login":"khm","nom":"khmayes","mail":"bke#live.fr","tel":"235684522"}];
$scope.nameList = [];
angular.forEach($scope.list,function(Obj,val){
$scope.nameList.push(Obj.nom);
});
you can use this code. in $scope.nameList you can get all names.
For this code you have to use angular js
Try
function getNames() {
return $http.get("/allU").then(function(result) {
return result.data.map(function(item) {
return item.nom;
});
});
}
getNames().then(function(data) {
$scope.names = data; //$scope.names = ["nesrine", "bilel", "ahmed", "khmayes"]
})
Related
I have an json from backend:
{
"_embedded" : {
"countries" : [ {
"id" : 1,
"name" : "Brazil",
"code" : "BR",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/countries/1"
},
"country" : {
"href" : "http://localhost:8080/api/countries/1"
},
"states" : {
"href" : "http://localhost:8080/api/countries/1/states"
}
}
}, {
"id" : 2,
"name" : "Canada",
"code" : "CA",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/countries/2"
},
"country" : {
"href" : "http://localhost:8080/api/countries/2"
},
"states" : {
"href" : "http://localhost:8080/api/countries/2/states"
}
}
}
}
}
And on frontend, I want to get data according to typescript interface:
interface Country {
id: number;
code: string;
name: string;
}
I have a code which maps above json to interface:
getCountries(): Observable<Country[]> {
return this.httpClient.get<CountriesResponse>(this.countriesUrl).pipe(
map(response => <Country[]>response._embedded.countries)
)
}
interface CountriesResponse {
_embedded: {
countries: Country[]
}
}
But after mapping method still returns data which is not present in typescript interface Country, I mean _links field.
Please suggest how to avoid it.
I actually found some solution but still thinks it could be done better:
getCountries(): Observable<Country[]> {
return this.httpClient.get<CountriesResponse>(this.countriesUrl).pipe(
map(response => {
const data: Country[] = response._embedded.countries
return data.map(c => ({
id: c.id,
name: c.name,
code: c.code
}))
})
)
}
I have a 3 layer nested document something like this.
{
"_id" : ObjectId("5b5acaf0589ff6bfb5dd091f"),
"date" : "2018/07/31",
"clock" : [
{
"time" : "10:12:02",
"values" : [
{
"name" : "A1003",
"value" : "777"
},
{
"name" : "A0001",
"value" : "888"
}
]
},
{
"time" : "13:12:02",
"values" : [
{
"name" : "A1003",
"value" : "111"
}
]
}
]
}
I'm able to sort the date by using $gte $lte as below and all values are fetched.
getData(name: string[], fromDate: string, toDate: string): Promise<{ message: string }> {
return this._mongoUtility.testDb
.then(db => {
let collection = db.collection('TestDoc');
let fromOnlyDate = fromDate.split(' ');
let toOnlyDate = toDate.split(' ');
return collection.find({
'date': {
$gte: `${fromOnlyDate[0]}`,
$lte: `${toOnlyDate[1]}`
}
}).toArray();
})
.catch(err => {
return Promise.reject({message: 'Data not found', err: err})
})
}
I want to filter by using time and again by name and should display the value.
I tried in many ways but I'm getting the result. Is there nay other method to do so in MongoDB? Kindly suggest.
Expected output should look like below
0:{date: "2018/07/31 10:12:02", value-A1003: "777", value-A0001: "888"}
1:{date: "2018/07/31 13:12:02", value-A1003: "111"}
you can use the aggregate framwork to achive a simmler result(you cant create attr by value)
db.getCollection('sss').aggregate([
{$unwind:'$clock'},
{$unwind:'$clock.values'},
{$project:{
date: {$concat:[ "$date" ,' ' , "$clock.time" ]},
value:'$clock.values.value',
name:'$clock.values.name'
}}
])
This function creates a playlist using the Spotify API. Which returns a body containing an 'id' that I need.
function createPlaylist(pc) {
let index = partyCodeExists(pc)
let at = token_arr[index]
let userID = user_ids[index]
var authOptions = {
url: 'https://api.spotify.com/v1/users/' + userID + '/playlists',
body: JSON.stringify({
'name': pc,
'description': 'Jukibox playlist',
'public': false
}),
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + at,
'Content-Type': 'application/json'
}
};
request.post(authOptions, function (error, response, body) {
console.log(body);
console.log(body.id);
});
};
The lower console logs give the following output:
{
"collaborative" : false,
"description" : null,
"external_urls" : {
"spotify" : "https://open.spotify.com/user/larsonadam-us/playlist/5pZ3C6ZRB3C9Tv9Z3EdA0g"
},
"followers" : {
"href" : null,
"total" : 0
},
"href" : "https://api.spotify.com/v1/users/larsonadam-us/playlists/5pZ3C6ZRB3C9Tv9Z3EdA0g",
"id" : "5pZ3C6ZRB3C9Tv9Z3EdA0g",
"images" : [ ],
"name" : null,
"owner" : {
"display_name" : null,
"external_urls" : {
"spotify" : "https://open.spotify.com/user/larsonadam-us"
},
"href" : "https://api.spotify.com/v1/users/larsonadam-us",
"id" : "larsonadam-us",
"type" : "user",
"uri" : "spotify:user:larsonadam-us"
},
"primary_color" : null,
"public" : true,
"snapshot_id" : "90UhGQhCi0Xq2vch8g/wrQ5BZoKK5cmIkiwybqJLUIsEAljI+L90YPzpD59T8zwP",
"tracks" : {
"href" : "https://api.spotify.com/v1/users/larsonadam-us/playlists/5pZ3C6ZRB3C9Tv9Z3EdA0g/tracks",
"items" : [ ],
"limit" : 100,
"next" : null,
"offset" : 0,
"previous" : null,
"total" : 0
},
"type" : "playlist",
"uri" : "spotify:user:larsonadam-us:playlist:5pZ3C6ZRB3C9Tv9Z3EdA0g"
}
undefined
Why does the second option display undefined?
Another note, I have body parser and it works in other areas of the code
The problem is that the return is a string. You need to handle the return before you get the ID. Try this.
console.log(body)
let bodyObject = JSON.parse(body)
console.log(bodyObject.id)
this is the value i'm sending through postman tool
{
"name" :[
{
"first_name" : "antony",
"second_name" : "grijan"
},{
"first_name" : "suresh",
"second_name" : "muthu"
}],
"allergy" : [
{
"condition" : "headache"
},
{
"condition" : "toothache"
}],
"communication" : [
{
"address" : "no 21 big street",
"phone" : "84"
},
{
"address" : "no 43 small street",
"phone" :"87"
}]
}
I got the value in my control layer and i'm trying to save it in my mongodb using mongoose, my model code is
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var patientSchema = new Schema({
name: {
first_name : { type : String, default : ''},
second_name : { type : String, default : ''}
},
allergy : {
condition : {type : String, default : ''}
},
communication : {
address : {type : String, default : ''},
phone : {type : String, default : ''}
}
});
var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;
My service layer code where i'm iterating is
var addDao = require('../dao/dao');
var async = require('async');
module.exports.addPatient = function(detail,callback) {
async.mapValues(detail,function(value,key,callback){
addDao.addPatient(value,function(data){
console.log(data);
console.log("calling");
callback(null, data);
})
}, function(err, result) {
// result is now a map of results for each key
console.log("inside func",result);
callback(result);
}
);
}
I have a console.log() in my service layer but it gives me only empty values, i think there is something wrong either with my model code or my iteration in my service layer!
I have this json structure an can't find a way to access the data values(data1, data2 and date), i'd like to have those values in an array than i can sort by date:
{
"07" : {
"07" : {
"data1" : "-1",
"data2" : "test",
"date" : "1995-07-07"
},
"08" : {
"data1" : "1",
"data2" : "test",
"date" : "1995-07-08"
},
"09" : {
"data1" : "-1",
"data2" : "test",
"date" : "1995-07-09"
},
"10" : {
"data1" : "-1",
"data2" : "test",
"date" : "1995-07-10"
}
},
"08" : {
"07" : {
"data1" : "1",
"data2" : "test",
"date" : "1995-08-07"
},
"08" : {
"data1" : "1",
"data2" : "test",
"date" : "1995-08-08"
},
"09" : {
"data1" : "1",
"data2" : "test",
"date" : "1995-08-09"
}
}
}
Because my keys aren't defined as constant i don't know what they'll be in advance.
Polyfill for Object.entries:
const reduce = Function.bind.call(Function.call, Array.prototype.reduce);
const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable);
const concat = Function.bind.call(Function.call, Array.prototype.concat);
const keys = Reflect.ownKeys;
if (!Object.values) {
Object.values = function values(O) {
return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []);
};
}
if (!Object.entries) {
Object.entries = function entries(O) {
return reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), []);
};
}
Code:
for (const [key, value] of Object.entries(myObject))
{
for (const [key2, value2] of Object.entries(value))
{
value2.data1;
value2.data2;
value2.date;
}
}
Instead Object.entries you can enumerate object like this.
for (var key in myObject)
{
for (var key2 in myObject[key])
{
myObject[key][key2].data1;
myObject[key][key2].data2;
myObject[key][key2].date;
}
}
You can get all the key names from your json as an Array by calling the method:
keys = Object.getOwnPropertyNames(jsonObj);
In your example this will return an array ['07', '08'] to get the actual objects from the name you can call:
keys.forEach((key) => {
objects = Object.getOwnPropertyDescriptor(jsonObj, key)
})
And then you can find the names of the keys of these objects and repeat
objects.forEach((object) => {
keys = Object.getOwnPropertyNames(object);
})