Underscore js to retrieve data from array - angularjs

I'm assigned a task to get data using underscore js.
This is my JSON :
$scope.myData= {
"buslist":
{
"code":"1",
"message":"Success",
"fromStationCode":"71",
"searchResult": [
{
"arrivalTime": "17:00:00",
"availableSeats": "42",
"boardingPointDetails": [
{
"code": "1631",
"name": "Koyambedu",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Nerkundram",
"time": "09:45:00"
}
]
},
{
"arrivalTime": "18:00:00",
"availableSeats": "32",
"boardingPointDetails": [
{
"code": "2084",
"name": "Adyar",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Madurai",
"time": "09:45:00"
}
]
}
]
}
}
From this I want only "name" field. By doing this :
$scope.bdata = _.pluck($scope.myTest.buslist.searchResult, 'boardingPointDetails');
I got all "boardingPointDetails". The result looks like:
[ [
{
"code": "2084",
"name": "Adyar",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Madurai",
"time": "09:45:00"
}
],[
{
"code": "1631",
"name": "Koyambedu",
"time": "09:30:00"
},
{
"code": "961296",
"name": "Nerkundram",
"time": "09:45:00"
}
],[
{
...
}
]
...
]
Help me to retrieve only "name" from this.

If you just want array of names like ['Koyambedu', 'Madurai'] then below code would work.
$scope.bdata = _.pluck($scope.myTest.buslist.searchResult, 'boardingPointDetails');
// Flatten the data.
$scope.flatbdata = _.flatten($scope.bdata, true);
$scope.flatbdata = $scope.flatbdata.filter(function(d){
return d != undefined && d.hasOwnProperty('name')
})
// map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results
$scope.names = $scope.flatbdata.map(function(d){
return d.name;
});
Refer below links :
http://underscorejs.org/#flatten
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

If you just want the array of names, here it is:
$scope.bdata = _.pluck($scope.myTest.buslist.searchResult, 'boardingPointDetails');
var res= _.flatten($scope.bdata);
res=_.pluck(res,'name');
console.log(res);

var temp = _.pluck(_.flatten($scope.bdata),'name')
temp will have ["Koyambedu", "Nerkundram", "Adyar", "Madurai"]

Try this.
$scope = {}; // in real project you don't need this. it's just for snippet.
$scope.myData = {
"buslist": {
"code": "1",
"message": "Success",
"fromStationCode": "71",
"searchResult": [{
"arrivalTime": "17:00:00",
"availableSeats": "42",
"boardingPointDetails": [{
"code": "1631",
"name": "Koyambedu",
"time": "09:30:00"
}, {
"code": "961296",
"name": "Nerkundram",
"time": "09:45:00"
}]
}, {
"arrivalTime": "18:00:00",
"availableSeats": "32",
"boardingPointDetails": [{
"code": "2084",
"name": "Adyar",
"time": "09:30:00"
}, {
"code": "961296",
"name": "Madurai",
"time": "09:45:00"
}]
}]
}
};
$scope.names = _.chain($scope.myData.buslist.searchResult).pluck("boardingPointDetails").flatten(true).map(function(item) {
return item.name;
}).value();
console.log($scope.names);
<script src="http://underscorejs.ru/underscore-min.js"></script>

Related

Angular: Get parent and specific child from JSON

I have this object:
elements120: {
"data": {
"name": "120",
"type": "120"
},
"children": [
{
"data": {
"name": "120A",
"type": "120A"
},
"children": []
},
{
"data": {
"name": "120B",
"type": "120B"
},
"children": []
},
{
"data": {
"name": "120C",
"type": "120C"
},
"children": []
}
]
}
I need to make some new Json as these below:
Json 1:
filtered120A{
"data": {
"name": "120",
"type": "120"
},
"children": [
{
"data": {
"name": "120A",
"type": "120A"
},
"children": []
}
]
}
Json 2:
filtered120B{
"data": {
"name": "120",
"type": "120"
},
"children": [
{
"data": {
"name": "120B",
"type": "120B"
},
"children": []
}
]
}
Json 3:
filtered120C{
"data": {
"name": "120",
"type": "120"
},
"children": [
{
"data": {
"name": "120C",
"type": "120C"
},
"children": []
}
]
}
I tried to do this in order to get only the first children node and delete the others (it's the only way it works me). For 120B and 120C i put as first child the value of the node that I needed for each case
this.filtered120A = utils.deepClone(this.elements120);
this.filtered120B = utils.deepClone(this.elements120);
this.filtered120C = utils.deepClone(this.elements120);
this.filtered120A = this.filtered120A.filter((element) => {
delete element.children[1];
delete element.children[2];
return true;
});
this.filtered120B = this.filtered120B.filter((element) => {
element.children[0] = element.children[1];
delete element.children[1];
delete element.children[2];
return true;
});
this.filtered120C = this.filtered120C.filter((element) => {
element.children[0] = element.children[2];
delete element.children[1];
delete element.children[2];
return true;
});
It works, but the code is not very elegant. I would like to know if there is any other better alternative.
Here you go:
function getOutputs(input) {
const outputs = [];
for (const child of input.children) {
outputs.push({
"data": {
"name": input.data.name,
"type": input.data.type
},
"children": [child]
});
}
return outputs;
}
const inputs = {
"data": {
"name": "120",
"type": "120"
},
"children": [
{
"data": {
"name": "120A",
"type": "120A"
},
"children": []
},
{
"data": {
"name": "120B",
"type": "120B"
},
"children": []
},
{
"data": {
"name": "120C",
"type": "120C"
},
"children": []
}
]
};
const outputs = getOutputs(inputs);
console.log(outputs[0]); // output1
console.log(outputs[1]); // output2
console.log(outputs[2]); // output3

MongoDB $push in Array of Array Error: No value exists in scope for the shorthand property 'elements'

I wish to add data into Elements but get error. How to solve this mongodb/typescript problem?
Attempt 1 Error: No value exists in scope for the shorthand property 'elements'. Either declare one or provide an initializer.ts(18004)
Attempt 1
async add<T extends { id: string; parentID: string, elementNum: number, name: string, link: string}>(collectionName: string, args: T) {
const db = await this.getDB();
const collection = db.collection(collectionName);
return new Promise((resolve, reject) => {
collection.updateOne({ id: args.id }, {$push: {elements[args.elementNum]: {id: uuid(), name: args.name, link: args.link, elements: [] }}}, (err, res) => {
if (err) {
reject(err);
}
resolve(res);
});
});
}
Attempt 2
changed the following
collection.updateOne({ id: args.id }, {$push: {elements: {id: uuid(), name: args.name, link: args.link, elements: [] }}},
Attempt 2 results in Null added in the end
{
"id": "1",
"name": "wk1",
"iconFile": "icon.png",
"elements": [
[
{
"id": "2",
"name": "element2",
"link": "https",
"elements": [
{
"id": "1",
"name": "element1",
"link": "https:"
}
]
}
],
[
{
"id": "3",
"name": "element3",
"link": "https://",
"elements": [
{
"id": "4",
"name": "w",
"link": "http:/"
}
]
}
],
[
{
"id": "3",
"name": "element3",
"link": "https://",
"elements": [
{
"id": "4",
"name": "w",
"link": "http://"
}
]
},
{
"id": "3",
"name": "element3",
"link": "https://",
"elements": [
{
"id": "4",
"name": "w",
"link": "http://www."
}
]
}
],
null,
]
}
What I want to achieve is the following
{
"id": "1",
"name": "wk1",
"iconFile": "icon.png",
"elements": [
[
{
"id": "2",
"name": "element2",
"link": "https",
"elements": [
{
"id": "1",
"name": "element1",
"link": "https:"
}
]
},
{
"id": "newid",
"name": "newname",
"link": "newlink"
"elements":[]
}
],
[
{
"id": "3",
"name": "element3",
"link": "https://",
"elements": [
.......
]
}
Demo - https://mongoplayground.net/p/Dnmg3lL2891
Use - $[]
The all positional operator $[] indicates that the update operator
should modify all elements in the specified array field.
The $[] operator has the following form:
{ <update operator>: { "<array>.$[]" : value } }
db.collection.update({ _id: 1, "add.id": "1"},
{ $push: { "add.$[].elements": { id: "3", name: "a", link: "" } } })
Demo to push array instead of object - https://mongoplayground.net/p/dh3NSutIv4-
db.collection.update({ _id: 1, "add.id": "1"},
{ $push: { "add.$[].elements": [{ id: "3", name: "a", link: "" }] } })
const args = {};
args.elementNum = 0;
const update = {
[`add.$[].elements.${args.elementNum}`]: {
a: 1
}
};
console.log(update);
//collection.updateOne({ id: args.id }, update); // use like this

DataTables - Load data from pre-defined JSON

I have a problem pointing dataTable to the right spot in the JSON. I receive a nested array:
{
"status": "ok",
"count": "7",
"msg ": "Operation Successful",
"data": [{
"contactHasServiceArea": true,
"issueCategories": [{
"id": "8",
"description": "Finance"
},
{
"id": "9",
"description": "Housing"
},
{
"id": "10",
"description": "International"
}
],
"cases": [{
"id": 31645,
"client_name": "Matthew",
"issue": "Assessment Completion",
"referral": null,
"opened_date": "10\/07\/2017",
"case_status": "Open"
}, {
"id": 31668,
"client_name": "Fanky ",
"issue": "Complex",
"referral": null,
"opened_date": "01\/07\/2017",
"case_status": "Open"
}]
}]
}
How do I point to the "cases" object? I'm sure this is simply, but I'm confused by the many options in the dataTables config.
I tried variations of data, dataSrc as well as data.cases or just cases, etc.
Thanks
$('#cases_table').DataTable( {
"ajax": "ajax/getCases",
"dataSrc" : "data.cases",
"data" : "cases",
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
You can configure like this:
$('#cases_table').DataTable( {
"ajax": {
"url": "ajax/getCases",
"dataSrc" : "data.cases"
},
"columns": [
{ "data": "client_name" },
{ "data": "issue" },
{ "data": "referral" },
{ "data": "opened_date" },
{ "data": "case_status" }
]
} );
datasrc points into the returns json. Remove the data option.

Get dynamic key value from an array angularjs

I have a mongo collection called settings
{
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}
Note: the values provided in my mongo is only for reference purpose.
Now I have generated an array with the records in settings collection
self.sample = function() {
self.settingsObj = {}
// console.log(self.settings)
_.each(self.settings, function(settings) {
//_.each(self.settings, function(settings) {
if (!self.settingsObj[settings.type]) {
self.settingsObj[settings.type] = []
}
self.settingsObj[settings.type] = settings.list
})
console.log(self.settingsObj)
}
When I console the settingsObj I get result like this in my console
Object {subject: Array[2], exam: Array[2]}
Now I want to loop this inside a scope variable
$scope.search = [{
"name": "",
"data": ""
}]
inside this name i want to get the object name in this situation subject,exam and inside loop i want to loop the arrays for subject and exam.
I tried another ._each, and I got the key and value but how can I loop them correctly.
Otherwise please help me in generating subject and exams as different array
I'm not very sure if I understand your question.
But if I see well you're using a Lodash.js library so I provide below script using a lodash:
I assume that you have settings variable like this:
var settings = [ {
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
,
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}];
And I create functions for process those settings:
function createSearch(settings){
return _(settings).flatMap(toSearchArray).value();
}
function toSearchArray(setting){
return _(setting.list).map("name").map(toSearchObject).value()
function toSearchObject(data){
return {
name: setting.type,
data: data
}
}
}
And when you call createSearch(settings)
you will receive this result:
[
{
"name": "subject",
"data": "Maths"
},
{
"name": "subject",
"data": " Physics"
},
{
"name": "exam",
"data": "Reading"
},
{
"name": "exam",
"data": "Fluency"
}
]
Hopefully this is what you need.

How can I get unique array from a collection of nested objects with lodash?

I have the following collection:
"items": [{
"id": 1,
"title": "Montrachet",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Espadeiro"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999"
},
{
"id": 2,
"title": "Montrachet2",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Chardonnay"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999",
}
]
I want to grab unique grapeTypes from that collection. The returning array shold be ["Chardonnay","Espadeiro"]
What is the best way to do it with lodash?
I think this combination of pluck, map and filter should do it:
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return _.filter(obj, function(prop) {
return prop.grapeType;
})[0].grapeType;
}).uniq().value();
console.log(result);
Check the demo run below.
// Code goes here
var obj = {
items: [{
"id": 1,
"title": "Montrachet",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [{
"description": "Kırmızı Şaraplar Desc"
}, {
"region": "Bordeaux"
}, {
"age": "16"
}, {
"producer": "Kayra"
}, {
"grapeType": "Espadeiro"
}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999"
},
{
"id": 2,
"title": "Montrachet2",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [{
"description": "Kırmızı Şaraplar Desc"
}, {
"region": "Bordeaux"
}, {
"age": "16"
}, {
"producer": "Kayra"
}, {
"grapeType": "Chardonnay"
}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999",
}
]
};
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return _.filter(obj, function(prop) {
return prop.grapeType;
})[0].grapeType;
}).uniq().value();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>
UPD. If grapeType can be missing from properties then the script should be
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return (_.filter(obj, function(prop) {
return prop.grapeType;
})[0] || {}).grapeType;
}).compact().uniq().value();
Here's one way to do it with lodash:
_(items)
.pluck('properties')
.map(function(item) {
return _.find(item, _.ary(_.partialRight(_.has, 'grapeType'), 1));
})
.pluck('grapeType')
.uniq()
.value();
First, you get the properties arrays using pluck(). Next, you use find() to get the first object in this array that has a grapeType property. This is done using has(), and partially-applying the argument to build the callback function.
Next, you use pluck() again to get the actual property values. Finally, uniq() ensures there are no duplicates.

Resources