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

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.

Related

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

Search in Embedded Documents in MongoDB?

I have document as shown
[
{
"Users": [
{
"Name": "Kartikey Vaish",
"_id": "1",
},
{
"Name": "Witcher Proxima",
"_id": "2",
}
],
"_id": "12",
},
{
"Users": [
{
"Name": "Witcher Proxima",
"_id": "2",
},
{
"Name": "Saga",
"_id": "4",
}
],
"_id": "13",
}
]
I want to search for those documents whose Users array has that particular ID
For Example if
ID == 1 // should return
[
{
"Users": [
{
"Name": "Kartikey Vaish",
"_id": "1",
},
{
"Name": "Witcher Proxima",
"_id": "2",
}
],
"_id": "12",
}
]
ID == 2 // should return
[
{
"Users": [
{
"Name": "Kartikey Vaish",
"_id": "1",
},
{
"Name": "Witcher Proxima",
"_id": "2",
}
],
"_id": "12",
},
{
"Users": [
{
"Name": "Witcher Proxima",
"_id": "2",
},
{
"Name": "Saga",
"_id": "4",
}
],
"_id": "13",
}
]
ID == 4 // should return
[
{
"Users": [
{
"Name": "Kartikey Vaish",
"_id": "1",
},
{
"Name": "Saga",
"_id": "4",
}
],
"_id": "13",
}
]
As you can see from above my query should return only those objects whose "Users" array contains an object with given ID. I tried this but it doesn't work.
const chats = await Chats.find({
Users: { $elemMatch: { _id: "1" } },
});
// this returns an empty array
const chats = await Chats.find({
Users: { $elemMatch: { Name: "Kartikey Vaish" } },
});
// this returns
[
{
"Users": [
{
"Name": "Kartikey Vaish",
"_id": "1",
},
{
"Name": "Witcher Proxima",
"_id": "2",
}
],
"_id": "12",
}
]
What am I doing wrong here?
Is it something related to _id paramter?
EDIT:
My Chats Schema looks like this -
const Chats = mongoose.model(
"Chats",
new mongoose.Schema({
Users: {
type: Array,
required: true,
default: [],
},
})
);
Update your schema as shown below
const Chats = mongoose.model(
"Chats",
new mongoose.Schema({
Users: [{
_id: {
type: String,
required: true, // Include only if needed!
unique: true // Include only if needed!
},
Name: {
type: String,
index: true // Include only if needed!
}
}]
})
);
If you do not explicitly mention _id MongoDB will create _id field as ObjectId.

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.

Underscore js to retrieve data from array

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>

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.

Resources