Count total with two criterias using Lodash - javascript

I can't figure out how I can count the total devices based on location and unique serial number.
{
"dates": [
{
"date": "Sep 1, 2014",
"devices": [
{
"model": "Canon",
"location": "Chicago",
"serialNum": "abc123"
},
{
"model": "Canon",
"location": "Chicago",
"serialNum": "xyz456"
},
{
"model": "HP",
"location": "New York",
"serialNum": "123456"
},
{
"model": "Brother",
"location": "Chicago",
"serialNum": "DEF777"
}
]
},
{
"date": "Sep 2, 2014",
"devices": [
{
"model": "Canon",
"location": "Chicago",
"serialNum": "abc123"
},
{
"model": "Canon",
"location": "Chicago",
"serialNum": "xyz456"
}
]
},
{
"date": "Sep 3, 2014",
"devices": [
{
"model": "Canon",
"location": "Chicago",
"serialNum": "xyz456"
},
{
"model": "Canon",
"location": "Chicago",
"serialNum": "stu789"
},
{
"model": "Epson",
"location": "NewYork",
"serialNum": "123456"
},
{
"model": "Epson",
"location": "NewYork",
"serialNum": "555555"
},
{
"model": "HP",
"location": "NewYork",
"serialNum": "987654"
}
]
}
]
}
I would like to capture the total number of unique devices per location
Chicago - 4
New York - 3

Here it is, in a single expression with lodash chaining syntax. The short version is you get all devices into one massive list, then you group them by location, then for each location eliminate the duplicate ids, then count the devices.
_(dates) //Begin chain
.pluck("devices") //get the device list for each date
.flatten() //combine all device lists into a master list
.groupBy("location") //group into an object of {"location": [devices]} pairs
.mapValues(function (devicesForLocation) { //replaces [devices] with a count of number of unique serial numbers
return _(devicesForLocation) //Begin chain
.pluck("serialNum") //get the serial number for each device
.uniq() //remove the duplicate serial numbers
.value() //End chain
.length; // get the count of unique serial numbers
}) // result is an object of {"location": countOfUniqueDevices} pairs
.value() //End chain
The final result is an object of the form: {"New York": 1, "NewYork": 3, "Chicago": 4}, though you could add another statement to print that out in string form, obviously.
I'd encourage you to run through this step-by-step to see the result of each step and understand what it's doing.

Related

How to map nested jsonb column in postgres

I have a column in my data base called extra_fields, it's of the jsonb type, I don't know what might be in there, since my user can send unlimited data, but I wanted to retrieve the keys and map this column. The problem is that I need it to be multidimensional (nested), is it possible in postgres?
Example of column value:
Row 1
{
"name": "John Doe",
"address":{
"city": "London",
"country": "UK"
},
"status": [{
"value": "Inactive",
"inserted_at": "2050-01-02 12:00:00"
},{
"value": "Active",
"inserted_at": "2050-01-01 12:00:00"
}]
}
Row 2
{
"name": "John Doe",
"phone": "+345 43456576"
"address":{
"city": "London",
"country": "UK"
},
"status": [{
"value": "Inactive",
"inserted_at": "2050-01-02 12:00:00"
},{
"value": "Active",
"inserted_at": "2050-01-01 12:00:00"
}]
}
And i need to return the keys like this:
[name, phone, address: [city, country], status: [value, inserted_at]]
Any suggestions on how I can do this?
My stacks are nestjs, typeorm and postgres.

Remove JSON parent element in JavaScript

I'm currently trying to code an application with javascript. It pulls data from a database and the response I'm getting is something like that:
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
But I need to have the JSON like that:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
How can I delete the parent values object in my JSON?
SHORT ANSWER:
Just access the values property like a JavaScript object.
LONG ANSWER:
You didn't post the JavaScript code snippet so it's quite difficult to give you an appropriate answer.
Assuming you have the following code:
const jsonString = getDataFromTheDB()
const jsonObject = JSON.parse(jsonObject) // still has the "values" layer
const values = jsonObject.values // what you want, without the "values" layer
// BONUS: Just in case you want to convert the object back to a JSON string but without the "values" layer
const valuesJSON = JSON.stringify(values, undefined, 2)
Based on this post :
just do this (consider json the variable that contains your json):
var key = "values";
var results = json[key];
delete json[key];
json = results;
console.log(json) will output the following:
[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
But you dont even have to do the last 2 steps of the code snippet above, you could also just directly use results variable and have the same output by console.log(results).
You could take the object and create a new variable with just the array.
var vals =
{
"values":[
{
"name": "Munich",
"location": "Germany",
"native_lang": "German",
},
{
"name": "London",
"location": "England",
"native_lang": "English",
},
{
"name": "Rome",
"location": "Italy",
"native_lang": "Italian",
}
]
}
var arr = vals.values;
console.log(arr);

Reshaping Flat JSON Structures with JavaScript

Currently, I have data in a flat JSON format. We need to convert it to a particular structure.
[
{
"Region":"WEST",
"District":"PACIFIC",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":374
},
{
"Region":"WEST",
"District":"MOUNTAIN",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":427
},
{
"Region":"SOUTH",
"District":"SOUTH WEST",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":422
},
{
"Region":"SOUTH",
"District":"SOUTH EAST",
"timestamp":"2018-12-28T00:00:00.000Z",
"Penetration":410
}
]
It should be as such. Also a constant "version": "v1" needs to be added to each object. The flattened result-set can be dynamic. So apart from timestamp key whatever key-value pair are present shall be pulled inside event object.
[
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":374,
"Region": "WEST",
"District": "PACIFIC"
}
},
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":427,
"Region": "WEST",
"District": "MOUNTAIN"
}
},
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":422,
"Region": "SOUTH",
"District": "SOUTH WEST"
}
}
{
"version": "v1",
"timestamp": "2018-12-28T00:00:00.000Z",
"event": {
"Penetration":410
"Region": "SOUTH",
"District": "SOUTH EAST"
}
}
]
You can simply make use of map method:
var data=[ { "Region":"WEST", "District":"PACIFIC", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":374 }, { "Region":"WEST", "District":"MOUNTAIN", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":427 }, { "Region":"SOUTH", "District":"SOUTH WEST", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":422 }, { "Region":"SOUTH", "District":"SOUTH EAST", "timestamp":"2018-12-28T00:00:00.000Z", "Penetration":410 }];
var result = data.map(({timestamp, ...events})=>({version:'v1',timestamp, events}));
console.log(result);

I have a json array object, I have to compare child most node and return complete array object having that particular child alone

const jsonArray = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}
The above mentioned json array object is all I have
Should compare all child nodes with "name": "Eternal Flame", and I should get output with the child node satisfying that condition.
`{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}`
Trying to return the data but not have an idea where i'm going wrong, please help me thank sin advance?
`jsonArray.map(member => member.members.forEach(details => {
const newArray = [];
if (details.name === 'Eternal Flame') {
return ***memberDetails***;
} else return null;}))`
First of all, your JSON structure is invalid (at least the one you've posted).
I'm going to assume the jsonArray is the object data of a squad, with members AND you're searching for a member (node) with the matching name Eternal Flame.
Secondly, your code will return the array with the same length as the members array with null everywhere except the matching node. To return only the matching node (I.e. member)...
jsonArray.members.filter(member => member.name === "Eternal Flame") [0]; // [0] Gets the first item of the matching array (Which should have a count of 1 anyway)
Assuming the name of each member is unique, you can use:
const newJson = {
...jsonArray,
members: [jsonArray.members.find(m => m.name === "Eternal Flame")]
}
This approach, first introduces the data of jsonArray in newJson and then sets the property members of newJson to an array which only contains the member you are looking for.
If name is not unique you can use:
const newJson = {
...jsonArray,
members: jsonArray.members.filter(m => m.name === "Eternal Flame")
}
With your data, in both cases the output is:
{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}

how to remove this object from array inside of object in array?

I am not sure how to form this question, but I will do my best.
I don't know how to remove object by _id from 'list:' part.
So, I have one array, and inside of that array I have list of objects,inside of these objects I have again array with objects, so I want to remove one object from that last array, how I can do that?
Cannot fix it for 2 days, I'm stucked!
Thanks!
[
{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [
{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [
{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
]
Using Vanilla JS:
function findAndRemove(data, id) {
data.forEach(function(obj) { // Loop through each object in outer array
obj.list = obj.list.filter(function(o) { // Filter out the object with unwanted id, in inner array
return o._id != id;
});
});
}
var data = [{
"_id": "599a1344bf50847b0972a465",
"title": "British Virgin Islands BC",
"list": [],
"price": "1350"
},
{
"_id": "599a1322bf50847b0972a38e",
"title": "USA (Nevada) LLC",
"list": [{
"_id": "599a1322bf50847b0972a384",
"title": "Nominee Member",
"service": "nominee-service",
"price": "300"
},
{
"_id": "599a1322bf50847b0972a385",
"title": "Nominee Manager & General Power of Attorney (Apostilled)",
"service": "nominee-service",
"price": "650"
},
{
"_id": "599a1322bf50847b0972a386",
"title": "Special Power of Attorney",
"service": "nominee-service",
"price": "290"
}
],
"price": "789"
},
{
"_id": "599a12fdbf50847b0972a2ad",
"title": "Cyprus LTD",
"list": [{
"_id": "599a12fdbf50847b0972a2a5",
"title": "Nominee Shareholder",
"service": "nominee-service",
"price": "370"
},
{
"_id": "599a12fdbf50847b0972a2a6",
"title": "Nominee Director & General Power or Attorney (Apostilled)",
"service": "nominee-service",
"price": "720"
},
{
"_id": "599a12fdbf50847b0972a2ab",
"title": "Extra Rubber Stamp",
"service": "other-service",
"price": "40"
}
],
"price": "1290"
}
];
// Empty almost all of list, except middle one
findAndRemove(data, "599a1322bf50847b0972a384");
findAndRemove(data, "599a1322bf50847b0972a386");
findAndRemove(data, "599a12fdbf50847b0972a2a5");
findAndRemove(data, "599a12fdbf50847b0972a2a6");
findAndRemove(data, "599a12fdbf50847b0972a2ab");
console.log(data);
Cleared everything except middle list, just for better visualization.
#Abhijit Kar your one is working perfectly, thanks mate!
How I can later splice this list?
When I was working with objects from first array, I did it like this :
var inventory = jsonArrayList;
for (var i = 0; i < inventory.length; i++) {
if (inventory[i]._id == deleteProductById) {
vm.items.splice(i, 1);
break;
}
}
It would be very helpful, thanks alot!
You can use Array.map and Array.filter to accomplish this. Detailed explanation in comments:
PS: This snippet uses ES6 arrow functions and spread operator
function removeById(arr, id) {
// Array.map iterates over each item in the array,
// and executes the given function on the item.
// It returns an array of all the items returned by the function.
return arr.map(obj => {
// Return the same object, if the list is empty / null / undefined
if (!obj.list || !obj.list.length) return obj;
// Get a new list, skipping the item with the spedified id
const newList = obj.list.filter(val => val._id !== id);
// map function returns the new object with the filtered list
return { ...obj, list: newList };
});
}
const oldArray = <YOUR_ORIGINAL_ARRAY>;
const newArray = removeById(arr, "599a12fdbf50847b0972a2a5");

Categories