Map key of object with array of object value - javascript

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.

Related

mongodb find method to display all data if array is empty

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})

How can check string value that contain in main string value in array by javascript

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);

Add JSON values from two different files into a single file

I just need to merge two files with the same list, but with different values on each file. Preferably in JavaScript
For example:
File 1
{"list1":{"a":1,"b":2}
{"list2":{"c":3,"d":4}
File 2
{"list1":{"a":5,"b":6}
{"list2":{"c":7,"d":8}
The desired result is
{"list1":{"a":6,"b":8}
{"list2":{"c":10,"d":12}
Sorry for the noob question, but the person who sent me the files should have done this themselves, but are currently unavailable. The files are too big to do by hand.
This is not very flexible code, but it would be far more work, to make something more dynamic. You would have to parse the objects recursevely and check if the property is an object and then jump deeper. Until ou find the values.
And please be aware that I'm not making any type checking whatsoever. If the data contains faulty data it is not cought properly. Also this code requires this exact structure. If your object contains other properties it might crash too.
// your data
const f1l1 = '{"list1":{"a":1,"b":2}}';
const f1l2 = '{"list2":{"c":3,"d":4}}';
const f2l1 = '{"list1":{"a":5,"b":6}}';
const f2l2 = '{"list2":{"c":7,"d":8}}';
var result1= JSON.parse(f1l1);
var result2= JSON.parse(f1l2);
//the names of the list as they appear in your real data *must* be the first object
const nameList1 = Object.keys(result1)[0];
const nameList2 = Object.keys(result2)[0];
//remove the list name
result1=result1[nameList1];
result2= result2[nameList2];
//get data from other file nd remove list name
const file2List1= JSON.parse(f2l1)[nameList1];
const file2List2= JSON.parse(f2l2)[nameList2];
// go through all items and sum them if the value is already in the list, else put it in for list1
for (var prop in file2List1) {
if (Object.prototype.hasOwnProperty.call(file2List1, prop)) {
if(Object.prototype.hasOwnProperty.call(result1, prop)){
result1[prop] = result1[prop] + file2List1[prop];
}else{
result1[prop] = file2List1[prop];
}
}
}
// and now for list2
for (var prop in file2List2) {
if (Object.prototype.hasOwnProperty.call(file2List2, prop)) {
if(Object.prototype.hasOwnProperty.call(result2, prop)){
result2[prop] = result2[prop] + file2List2[prop];
}else{
result2[prop] = file2List2[prop];
}
}
}
//put names of lists back in.
result1 = {[nameList1]:result1};
result2 = {[nameList2]:result2};
//check results:
console.log("input data:");
console.log(JSON.parse(f1l1));
console.log(JSON.parse(f1l2));
console.log(JSON.parse(f2l1));
console.log(JSON.parse(f2l2));
console.log("output data:");
console.log(result1);
console.log(result2);
You can try this out
newList = list1.concat(list2);

Merge and create an unique case sensitive array in javascript

It's a complicated scenario but will try to explain as much as possible. I have one object or arrays and one array. Now i have to compare selectedmodel values with mappedmodels, if the value(Case insensitive) matches with that object then fetch all the values of it and push it into selected model and combine both. Hope the example will clear what i am trying to achive.
var mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] };
var selectedModels = ['CC605', 'tc76'];
var desiredOutput = ["CC605", "tc76", "cc605", "cC605"];
I already wrote a solution to achieve it but i need a better code in terms of performance. Here is the solution:
function combineModelCases(selectedModels) {
const modelCases = [];
selectedModels.forEach(elm => {
const existingModels = mappedModels[elm.toUpperCase()];
if (existingModels) {
for (const key of existingModels) {
if (elm.toUpperCase() !== key) {
modelCases.push(key);
}
}
}
});
return selectedModels.concat(modelCases);
}
Here is Fiddle
I am using typescript and underscore js for your references. Any help would be very helpful.
You could use flatMap to get a flattened array of values for each key in selectedModels. Then, create a Set to get a unique collection models. Use Array.from() to convert the set to an array.
const mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] },
selectedModels = ['CC605', 'tc76'];
const models = selectedModels.flatMap(m => mappedModels[m] || []),
unique = Array.from(new Set([...selectedModels, ...models]));
console.log(unique)
you can do the following, :
var mappedModels = { 'CC605': ['cc605', 'CC605', 'cC605'], 'TC75X': ['TC75X'] };
var selectedModels = ['CC605', 'tc76'];
var desiredOutput;
function combineModelCases(selectedValue){
if(mappedModels.hasOwnProperty(selectedValue)){
desiredOutput = [... new Set([...mappedModels[selectedValue], ...selectedModels])]
return desiredOutput;
}
}
console.log(combineModelCases('CC605'));
here is the working demo : https://jsfiddle.net/wzo4d6uy/2/:

How to loop through an array and get the name corresponding to id and assign the result to another array

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);

Categories