Node.js | Remove element in json - node.js

I have a json like this:
var myjson = [
{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
},
{
"id": "4"
},
{
"id": "5"
}
];
I want the incoming id removed from myjson when app.delete() is triggered.
Forexample incoming id = 3. Then myjson's new look:
var myjson = [
{
"id": "1"
},
{
"id": "2"
},
{
"id": "4"
},
{
"id": "5"
}
];

You can use Array.prototype.filter() to do this like the code below:
const removeItem = (id) => myjson.filter(item => item !== id);

Related

Merge multiple object arrays and removing duplicates based on optional property

Say if there are arrays like:
const arr1 = [
{ "id": "1", "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr2 = [
{ "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr3 = [
{ "id": "1", "type": "sales" },
{ "type": "sales" },
{ "type": "finance" }
]
As you can see, id is optional. I need to merge arrays in such way that uniqueness should be based on id if present, else entire rest of the object.
ex. here merged array would be:
[
{ "id": "1", "type": "sales" },
{ "type": "sales" },
{ "id": "2", "type": "finance" },
{ "type": "finance" }
]
loadash has .unionBy but optional uniqueness doesn't work.
const result = _.unionBy(arr1, arr2, arr3, 'id')
Probably I have to iterate through each, but I was wondering if there is any simpler alternative for this.
Instead of _.unionBy you can use _.unionWith which accepts a custom comparator. The logic for comparison is:
Compare by ID if both items have an ID.
Compare by type if both items do not have an ID.
Consider them different if one has an ID the other not.
const arr1 = [
{ "id": "1", "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr2 = [
{ "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr3 = [
{ "id": "1", "type": "sales" },
{ "type": "sales" },
{ "type": "finance" }
]
const result = _.unionWith(arr1, arr2, arr3, (item1, item2) => {
const item1HasId = _.has(item1, "id");
const item2HasId = _.has(item2, "id");
if (item1HasId && item2HasId) //if both have ID...
return item1.id === item2.id; // ...compare by ID
if (!item1HasId && !item2HasId) //if neither has ID...
return item1.type === item2.type; // ...compare by type
return false; // otherwise not equal
});
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>

Best way to format the JSON content in Node.js application

I am working on an NODE JS based application. Trying to figure out any easy method to get my expected result. Had tried few ways, but after reframing the JSON content not able to add the key state.
My content JSON content is in this format
[
{
"item": {
"property1": "aa",
"property2": "22"
},
"state": {
"item": {
"state": "AS",
"country": "US",
"reason": "1"
}
},
"province": {
"item": {
"name": "AS",
"method": "table",
"conf": "3"
}
}
},
...
]
Requirement is to format state as below,
{
...
"state": [
{
"item": {
"state": "AS",
"country": "US",
"reason": "1"
}
}
],
...
}
I want to format the state content. The content is expected to be an array of JSON content. After formatting state, the orginal json content need to be modified with the new content of state. The issue faced here is after formatting not able to add the key state back to the orginal JSON content.Same is the expectation for province.
Requesting support from All...Thanks in Advance....
Below is the code i had written, but the expected result is not obtained.Can anyone help me in identifying were i have gone wrong
var testJson = JSON.parse(jsonData);
var tempFinal = [];
for(let i =0; i<testJson.length; i++) {
let itemData = {};
itemData.item = testJson[i].item;
tempFinal.push(itemData);
var state = [];
state.push( testJson[i].state);
let stateData = {};
stateData.state = state;
tempFinal.push(stateData);
var service = [];
service.push( testJson[i].service);
let serviceData = {};
serviceData.service = service;
tempFinal.push(serviceData);
}
The result obtained is
[
{
"item": {
"protocol": "tcp",
"portid": "22"
}
},
{
"state": [
{
"item": {
"state": "filtered",
"reason": "no-response",
"reason_ttl": "0"
}
}
]
},
{
"service": [
{
"item": {
"name": "ssh",
"method": "table",
"conf": "3"
}
}
]
}
]
Expected is
[
{
"item": {
"a": "a",
"a": "a"
},
"state": [
{
"item": {
"c": "b",
"e": "f",
"reason_ttl": "0"
}
}
],
"service": [
{
"item": {
"name": "q",
"method": "table",
"d": "e"
}
}
]
}
]
You can try this one
//jsonData is your original json data
jsonData.map((obj1=>{
//updating state data
obj1.state=[obj1.state];
}));
//finally print it.
console.log(jsonData);

sending json data to mongodb

I have some json data which i want to send to mongodb using kafka consumer in nodejs. I want different collection for each part of the JSON data. How do i do that? Any help would be appreciated
[
{
"`Bin_details`": {
"Device_ID": "1"
},
"Device_Status": {
"Filled_status": "0.097",
"TimeStamp": "15:56:23"
},
"date": "15-6-2021"
},
{
"Bin_details": {
"Device_ID": "2"
},
"Device_Status": {
"Filled_status": "0.086",
"TimeStamp": "15:56:23"
},
"date": "15-6-2021"
},
{
"Bin_details": {
"Device_ID": "3"
},
"Device_Status": {
"Filled_status": "0.087",
"TimeStamp": "15:56:23"
},
"date": "15-6-2021"
},
You can create a new collection with a loop like this:
const jsonData = [
{
"`Bin_details`": {
"Device_ID": "1"
},
"Device_Status": {
"Filled_status": "0.097",
"TimeStamp": "15:56:23"
},
"date": "15-6-2021"
},
{
"Bin_details": {
"Device_ID": "2"
},
"Device_Status": {
"Filled_status": "0.086",
"TimeStamp": "15:56:23"
},
"date": "15-6-2021"
},
{
"Bin_details": {
"Device_ID": "3"
},
"Device_Status": {
"Filled_status": "0.087",
"TimeStamp": "15:56:23"
},
"date": "15-6-2021"
}
];
// DB Setup
const { MongoClient } = require('mongodb');
const client = new MongoClient(DB_CONNECTION_STRING, { useUnifiedTopology: true });
await client.connect();
const db = await client.db();
// Loop to create collections
let index = 0;
for(let eachData of jsonData){
const collectionName = `Collection-${index}`
await db.createCollection(collectionName);
index++;
}

How to get Nested data in node js

I want to get items per category in node js. how to get it. Here is the example that i want
"status": true,
"total_results": 4,
"categories": [
{
"id": 2,
"name": "Category 1",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
},
{
"id": 4,
"name": "Category 2",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
}
]
}
Here is the code i write for getting above array result in nodejs
pool.query(`Select * FROM categories WHERE catalog_id = '${fields.catalog_id}'`, async (error, result, field) => {
if (error) { // if error
console.log(error);
return false;
}
var Catarr = result.map((item,index)=>item.id)
pool.query(`Select * FROM items WHERE category_id IN (${Catarr})`, async (error, menuItems, field) => {
if (error) { // if error
console.log(error);
return false;
}
var parsed_items = [];
await result.forEach((item,index)=>{
var items = menuItems.filter((p_item)=>p_item.category_id == item.id)
var obj = {
name: item.name,
id: item.id,
items
}
parsed_items.push(obj)
})
res.status(200).json({status:true,total_results:result.length,categories:parsed_items});
});
});
Sharing my suggestion as per my understanding; Please refer to below code snippet:
const data={ "status": true,
"total_results": 4,
"categories": [
{
"id": 2,
"name": "Category 1",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
},
{
"id": 4,
"name": "Category 2",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
}
]
};
const expectedResult=data.categories.reduce((iter, item)=>{
iter[item.name]=item.items? item.items.length : 0; // we can use item.id if required
return iter;
}, {});
alert(JSON.stringify(expectedResult));
console.log('Items per category - ',expectedResult);

Add response to each item for loop in node.js and postgres

I have an array of schools like this:
{
"schools": [
{
"name": "S1",
"id": 1
},
{
"name": "S2",
"id": 2
},
{
"name": "S3",
"id": 3
}
]
}
and each school has schedule. To Get that I iterate the schools array in a promise and when I get the response I get an array like this
{
"schools": [
{
"name": "S1",
"id": 1
},
{
"name": "S2",
"id": 2
},
{
"name": "S3",
"id": 3
}
],
"schedules": [
[],
[
{
"id_schedule": 58,
"hour1": "13:00:00",
"hour2": "20:00:00",
"id_schools_schedule": 2
}
],
[
{
"id_schedule": 59,
"hour1": "06:30:00",
"hour2": "22:30:00",
"id_schools_schedule": 3
}
]
]
}
I want to know. how to asign the response of each item?
this is my code
for (var i =0; i < datosRes.schools.length; i++){
array_horarios.push(ObtSchedule(datosRes.schools, i))
}
Promise.all(array_horarios).then(response => {
datosRes.horarios = response;
eq.local = data;
}).catch(err => {
return res.json(200,{"datos":datosRes});
})
function ObtHorario(schools, i){
return new Promise(function(resolve, reject){
var id_school = schools[i].id;
Mod_Schedule.obtSchedule(id_school,function(error, data){
if(error || data.error){
errorDB = {"error_log": error, "error_data": data.error};
reject(errorDB)
}else{
resolve(data)
}
})
})
}
What I am doing wrong?
I get the response but only I want to add to each item of schools the schedules
Thanks in advance
First thing first:
You can send ONE response to ONE request. So your question to send multiple responses is invalid.
Here's what you can do, you can get the array of schools with their schedules.
If you are using MongoDB, here's what you can do:
Using Aggregate query:
db.schools.aggregate([
{
$match: {} // Your condition to match schools here
},
{
$lookup: {
from:"schedules",
localField: id,
foreignField: id_schools_schedule,
as: "schedulesData"
}
},
]);
Here, you will get data something like:
[
{
"name": "S1",
"id": 1,
"schedulesData": []
},
{
"name": "S2",
"id": 2,
"schedulesData": [{
"id_schedule": 58,
"hour1": "13:00:00",
"hour2": "20:00:00",
"id_schools_schedule": 2
}]
},
{
"name": "S3",
"id": 3,
"schedulesData": [
{
"id_schedule": 59,
"hour1": "06:30:00",
"hour2": "22:30:00",
"id_schools_schedule": 3
}
]
}
]

Resources