Let say I have dynamic array
const branddata = ["adidas", "nike", "puma"]
//this data can be sometime empty too like
// const branddata = []
//now I want to search all the product with brands like
const product = productmodel.find({brand:branddata})
The problem is, this thing works when branddata array is not empty and it gives me the product.
But when it is empty the find method search for a brand which is equal to "" and gives me zero product.
I want all the products to be displayed if branddata is empty.
How can I get this using $regex or any other?
you can check branddata is empty or not, and create query object based on it, like this
let q=(branddata && branddata.length>0 )?{brand:branddata}:{};
const product = productmodel.find(q);
when you have multiple params,you can do something like this
let params={
"brand":branddata,
"price":pricedata,
"gender":genderdata
}
let q={};
Object.Keys(params).forEach((t)=>{
if(params[t] && params[t].length>0 ){
q[t]=params[t]
}
})
const product = productmodel.find(q);
Finally found a solution with a function-based approach
$in is used to find document data which are in the array and $nin is used to find document data which are not in the array (basically when array is empty)
const branddata = ["adidas", "nike", "puma"]
const pricedata =["100"]
const genderdata =["male","female"]
const queryfunc = (value)=>{
var q = {}
if(value==''){
q["$nin"]=value;
}
else{
q["$in"]=key;
}
return q
}
const brand=queryfunc(branddata)
const price=queryfunc(pricedata)
const gender=queryfunc(genderdata)
const product = productmodel.find({brand,price,gender})
Related
I've tried a few stack examples. an i am still just rewriting what i was hoping to be adding to ... mainly we have a list of check box items each time you check it i would like existing items to turn into a list of those object so we can use them on a 'comparing' page
const handleChange = () => {
localStorage.setItem("item", JSON.stringify(products)); <-- works as expected
var existingItems: any[] = [];
existingItems?.push({ products });
localStorage.setItem("compareItems", JSON.stringify(existingItems));
};
existingItems is always = to products i want existing items to = [{item}, {item},] and so on
detail of what products would be:
products (object of key and values frm api) = {name: "Product 1", description: "Product 1", isActiveForEntry: true, displayRank: 0, sku: "ABC123"}
You have to get the existing items first before defaulting to an empty array:
const existingItems: any[] = JSON.parse(localStorage.getItem("compareItems")) ?? [];
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
existingItems.push({ products });
localStorage.setItem("compareItems", JSON.stringify(existingItems));
See nullish coalescing operator for what the ?? means.
At each method invocation, you are initializing existingItems object then storing its value with one item being the products hence the stored object will only hold one item at a time.
You should retrieve the compareItems stored value being your existingItems then append the new products objet to it:
const handleChange = () => {
localStorage.setItem("item", JSON.stringify(products));
const compareItems = JSON.parse(localStorage.getItem("compareItems"));
var existingItems: any[] = compareItems ? compareItems : [];
existingItems.push({ products });
localStorage.setItem("compareItems", JSON.stringify(existingItems));
};
I want to check user.uid that contain or not in combined user ids.
here is combined ids in arrays
getid Array [
"E8R52y6dD8XI3shXhnhS9pVzUpe26Lf5bHwzCSbI2bmoMv7KuduMGwe2",
"KgRwTDgenjYpODPxRaldDQy9nnH36Lf5bHwzCSbI2bmoMv7KuduMGwe2",
"pNv0iKlZ6xVOl0fFOZSoXJoPuVx2E8R52y6dD8XI3shXhnhS9pVzUpe2",
]
here is user.uid
pNv0iKlZ6xVOl0fFOZSoXJoPuVx2
I want to get result is my user.uid is in or not in this combined Id arrays.
const uid = user.uid in getId ? yes : no
(or ) how can check this condition .I not know.
I not want to remove my user.uid from combined id , I just want to check my user.uid is in or not in this combined Id.
can someone help me?
You can simply check using array functions like filter, find , findIndex, some
let array = [
"E8R52y6dD8XI3shXhnhS9pVzUpe26Lf5bHwzCSbI2bmoMv7KuduMGwe2",
"KgRwTDgenjYpODPxRaldDQy9nnH36Lf5bHwzCSbI2bmoMv7KuduMGwe2",
"pNv0iKlZ6xVOl0fFOZSoXJoPuVx2E8R52y6dD8XI3shXhnhS9pVzUpe2",
];
let userId = 'pNv0iKlZ6xVOl0fFOZSoXJoPuVx2';
const exist = array.filter(id => id.includes(userId)).length > 0;
//Using some method
const exist1 = array.some(id => id.includes(userId));
console.log(exist, exist1);
If you just want to get a boolean value indicating if element is in the array or not, you can simply use getId.includes(user.uid).
Check out this MDN link if want to know more about Array.prototype.includes()
const arr = [ "E8R52y6dD8XI3shXhnhS9pVzUpe26Lf5bHwzCSbI2bmoMv7KuduMGwe2", "KgRwTDgenjYpODPxRaldDQy9nnH36Lf5bHwzCSbI2bmoMv7KuduMGwe2", "pNv0iKlZ6xVOl0fFOZSoXJoPuVx2E8R52y6dD8XI3shXhnhS9pVzUpe2",
]
const invalidId = 'pNv0iKlZ6xVOl0fFOZSoXJoPuVx2'
const validId = "E8R52y6dD8XI3shXhnhS9pVzUpe26Lf5bHwzCSbI2bmoMv7KuduMGwe2"
const arrayHasInvalidId = arr.includes(invalidId)
const arrayHasValidId = arr.includes(validId)
console.log(arrayHasInvalidId,arrayHasValidId);
Suppose I have an array of object as:
const bookDetails = [{"author":"john","email":"john#gmail.com","readingTime":"121"},
{"author":"romero","email":"romero#gmail.com","readingTime":908},
{"author":"romero","email":"alpha#gmail.com","readingTime":1212},
{"author":"buck","email":"buck#gmail.com","readingTime":1902},
{"author":"buck","email":"bujor#gmail.com","readingTime":12125},
{"author":"romero","email":"romero#gmail.com","readingTime":500},
{"author":"john","email":"john#gmail.com","readingTime":10},
{"author":"legend","email":"legend#gmail.com","readingTime":12}
{"author":"john","email":"john#gmail.com","readingTime":1890}]
I have an object as:
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
I want to replace emailId with corresponding author.
So my expected O/P should be: {"romero":1212,"john":1248,"buck":909}
If anyone needs any further information please let me know.
You can generate a new object by iterating over bookDetails and look up the values from toMatch
Like this
const bookDetails=[{"author":"john","email":"john#gmail.com","readingTime":"121"},{"author":"romero","email":"romero#gmail.com","readingTime":908},{"author":"romero","email":"alpha#gmail.com","readingTime":1212},{"author":"buck","email":"buck#gmail.com","readingTime":1902},{"author":"buck","email":"bujor#gmail.com","readingTime":12125},{"author":"romero","email":"romero#gmail.com","readingTime":500},{"author":"john","email":"john#gmail.com","readingTime":10},{"author":"legend","email":"legend#gmail.com","readingTime":12},{"author":"john","email":"john#gmail.com","readingTime":1890}]
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
const result = {};
for (const detail of bookDetails) {
const {email, author} = detail;
if (email in toMatch) {
result[author] = toMatch[email];
}
}
console.log(result);
Ah, you want to matching names from emails based on the array of objects. Is that right? If so..
const bookDetails=[{"author":"john","email":"john#gmail.com","readingTime":"121"},{"author":"romero","email":"romero#gmail.com","readingTime":908},{"author":"romero","email":"alpha#gmail.com","readingTime":1212},{"author":"buck","email":"buck#gmail.com","readingTime":1902},{"author":"buck","email":"bujor#gmail.com","readingTime":12125},{"author":"romero","email":"romero#gmail.com","readingTime":500},{"author":"john","email":"john#gmail.com","readingTime":10},{"author":"legend","email":"legend#gmail.com","readingTime":12},{"author":"john","email":"john#gmail.com","readingTime":1890}]
function namesMap(object,list){
//to save complexity(assuming the array is huge), I'd just loop through the list once to get the data I need
var obj={} //relates emails to names
list.forEach(item=>{
obj[item.email]=item.author
})
var toReturn={}
Object.keys(object).forEach(email=>{
toReturn[obj[email]]=object[email] //email to name conversion
})
return toReturn
}
//example usage
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
console.log(namesMap(toMatch,bookDetails))
There you go, I'm 100% you can do this easier, but this is the fastest response that came to my mind:
function changeData(bookDetails){
let returnableObject = {};
bookDetails.forEach(book => {
returnableObject[book.author] = book.readingTime
})
return returnableObject;
}
*EDIT -> This would work if your Author name IS UNIQUE if the author name is not unique you should change the name or maybe use an array of objects, not an object with multiple values...
*EDIT 2 -> I think I didnt understand your question.
I have a large json file that needs to have to "fields" merged in to an array in order to store to firestore.
Here a screenshot to show what I mean. What i have:
What I need:
As you can see GRP1D and GRP2D where merged in to an array. The json has 15000 entries so doing it manually is not an option
You can write a script using NodeJS to edit this huge file similar to the following:
const largeJson = require('./largeJson.json');
// I am assuming here that the large JSON file is an array of objects
const mergedJson = largeJson.map(obj => {
const objEditted = { ...obj, GRP1D: [ obj.GRP1D, obj.GRP2D ] };
delete objEditted.GRP2D;
return objEditted;
});
// mergedJson now holds an array of objects which merge the fields
// GRP1D and GRP2D as you described in the example
Here is small code snippet using the spread operator
const your_data = require("./your_data/ file/path");
const prepare_func = (your_data)=>{
let temp = {...your_data,"GRP1D":[your_data["GRP1D"],your_data["GRP2D"]]};
return temp;
}
let new_data = prepare_func(your_data);
I am new to typescript .please help me in doing this.
I have an array as below.
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
i want to loop through pets and get the names of animals from another array Category where
let category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},{id:"4",name:"Goat"}]
get output as below,
// expected output,
newpets=[{id:"1",name:"Dog"},{id:"2",name:"Cats"}]
Try this out. I have used, Array map() and Array find() to achieve this.
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
let category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},{id:"4",name:"Goat"}]
let newPets = pets.map(eachPet => {
return category.find(eachCat => eachPet.id === eachCat.id)
})
console.log(newPets)
There can be many ways to do it. One way
let pets=[{id:"1",name:"animal"},{id:"2",name:"animal"}];
let Category = [{id:"1",name:"Dog"},{id:"2",name:"Cats"},{id:"3",name:"Cows"},
{id:"4",name:"Goat"}];
var newpets = [];
pets.forEach(pet => {
let animalType = Category.find(cate => pet.id === cate.id );
newpets.push({id:pet.id, name: animalType.name});
})
console.log(newpets);