IndexedBD select objects from upper to lower? - javascript

For example:
const customerData = [
{ id: 444, name: "Bill", age: 35, email: "bill#company.com" },
{ id: 5555, name: "Donna", age: 32, email: "donna#home.org" },
{ id: 666, name: "Cat", age: 2, email: "cat#home.org" },
{ id: 888, name: "Gandalf", age: 21000, email: "gandalf#home.org" }
];
function getDataByRange(db, table, index, lower, upper, fun){
var data = [];
var tx = db.transaction(table, "readonly");
var store = tx.objectStore(table);
var index = store.index(index);
var boundKeyRange = IDBKeyRange.bound(lower, upper, false, false);
var request = index.openCursor(boundKeyRange);
request.onsuccess = function() {
var cursor = request.result;
if (cursor) {
data.push(cursor.value);
cursor.continue();
} else {
fun(data);
}
};
}
How to get next results: Gandalf, Bill, Donna, Cat?
Now I get something like: Cat,Donna, Bill, Gandalf.
Thanks for any suggestions!

The openCursor method accepts two arguments. The second argument is optional and specifies the direction of the cursor. Because it is optional, you rarely see the second argument specified in example code, so maybe that is why it is confusing.
There are four possible direction values: next, prev, nextUnique, and prevUnique. You specify the argument as a string. next is the implied default argument.
So, use openCursor(boundKeyRange, 'prev') to iterate in reverse.

Related

Compare and get difference from two object for patch api request in react js?

i m having two objects previous and new one, i trying to compare and get difference for those objects, send to as patch payload from patch api,
compare each properties in object if any of the property has any difference i want all those difference in new object as payload
How can i achieve this please help me find the solution?
Is there any lodash method for this solution?
let obj = {
Name: "Ajmal",
age: 25,
email: "ajmaln#gmail.com",
contact: [12345678, 987654321],
address: {
houseName: "ABC",
street: "XYZ",
pin: 67891
}
}
let obj2 = {
Name: "Ajmal",
age: 25,
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
houseName: "ABC",
street: "XYZ",
pin: 111
}
}
result payload i m expecting would look like
let payload = {
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
pin: 111
}
}
Mista NewbeedRecursion to your service:
const compare = (obj1, obj2) => {
const keys = Object.keys(obj1);
const payload = {};
keys.forEach((el) => {
const first = obj1[el];
const second = obj2[el];
let check;
if (first !== second) {
if (first instanceof Object && !(first instanceof Array))
check = compare(first, second);
payload[el] = check || second;
}
});
return payload;
};
Here is a approach with immer that may guide you to a proper solution
This is not a generic approach but makes things easier by relying on immer
import produce, { applyPatches, enablePatches } from "immer";
import { difference } from "lodash";
// once in your app
enablePatches();
let obj = {
Name: "Ajmal",
age: 25,
email: "ajmaln#gmail.com",
contact: [12345678, 987654321],
address: {
houseName: "ABC",
street: "XYZ",
pin: 67891
}
};
let obj2 = {
Name: "Ajmal",
age: 25,
email: "something#gmail.com",
contact: [12345678, 11111111],
address: {
houseName: "ABC",
street: "XYZ",
pin: 111
}
};
Gettig the patch updates
let fork = { ...obj };
let changes = [];
const updatedItem = produce(
fork,
(draft) => {
// object specific updates
draft.Name = obj2.Name;
draft.age = obj2.age;
draft.email = obj2.email;
draft.address.houseName = obj2.address.houseName;
draft.address.street = obj2.address.street;
draft.address.pin = obj2.address.pin;
const originalContact = original(draft.contact);
const contactDiff = difference(obj2.contact, originalContact);
console.log("diff", contactDiff);
if (contactDiff?.length) {
draft.contact = contactDiff;
}
},
(patches) => {
changes.push(...patches);
}
);
//Problem here => default values need to be given to state
// so the default values need to be excluded from the patch
let state = { contact: [], address: {} };
const patch = applyPatches(state, changes);
console.log("patch", patch);
logs changes op
contact: Array(1)
0: 11111111
address: Object
pin: 111
email: "something#gmail.com"
Hope this helps you in some way
Cheers

How to remove an object from an array if it has the letter a?

I need to make a function that receives 2 parameters, the first one is an array of a list of users that must contain first name, last name and phone numbers, at least 3 of those users must start with the letter "a", the second parameter is a callback. You must process the array and delete all the users whose name starts with the letter "a". Then send the new processed array to the callback. The callback must show in console, the list of all the names, concatenating first and last name.
const users =
[{
name: 'Diego',
lastname: 'Garcia',
phone: '12343'
},
{
name: 'Camilo',
lastname: 'Garcia',
phone: '12343'
}, {
name: 'ana',
lastname: 'Rodriguez',
phone: '02343'
}, {
name: 'anastasia',
lastname: 'Zapata',
phone: '42343'
}, {
name: 'alejandra',
lastname: 'Perez',
phone: '52343'
}];
const operation2 = (list) => {
let x = [];
let callback = {};
callback = list.find(element => element.name.charAt(0) == 'a');
let l = list.indexOf(callback)
let g = list[l];
console.log(g)
if (callback) {
x = list.splice(l, 1)
} return list
}
console.log(operation2(users))
The code that I made does not work, it is not eliminating all the names that begin with "a", it only eliminates the first object of the array.
Array.find only finds the first match, you should probably filter out the elements you don't want:
const result = list.filter(element => element.name.charAt(0) !== 'a');
const users =
[{
name: 'Diego',
lastname: 'Garcia',
phone: '12343'
},
{
name: 'Camilo',
lastname: 'Garcia',
phone: '12343'
}, {
name: 'ana',
lastname: 'Rodriguez',
phone: '02343'
}, {
name: 'anastasia',
lastname: 'Zapata',
phone: '42343'
}, {
name: 'alejandra',
lastname: 'Perez',
phone: '52343'
}];
function func(list, callback) {
let users = list.filter(u => !u.name.toLowerCase().startsWith('a'));
callback(users)
}
func(users, (users) => {
console.log(users)
})

js: How to filter object keys from an array of objects? [duplicate]

This question already has answers here:
Remove property for all objects in array
(18 answers)
Closed 7 months ago.
I have an array similar to this one
let array = [
{
name: "1-name",
age: 18,
direction: "jsjs"
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs"
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs"
}
]
and i want to filter it based on its keys to get an array like this
[
{
name: "1-name",
direction: "jsjs"
},
{
name: "2-name",
direction: "jsjsjs"
},
{
name: "3-name",
direction: "jsjsjsjs"
}
]
Can you please help me i've try to solve it with no success
You can you the array map function.
See an example here:
const arr = [
{
name: "1-name",
age: 18,
direction: "jsjs",
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs",
phone: 7182718
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs",
phone: 7182718
}
]
const result = arr.map(({ name, direction }) => {
return {
name,
direction
};
})
console.log(result);
You Can Try This Code:
let newArr = [];
array.forEach((e) => {
newArr.push({ name: e.name, direction: e.direction });
});
The map method will work. How you implement this depends on whether you want to create a new array result with the previous objects deleted, or simply return the ones you want to keep. This will create a new array your original array will remain unaffected.
array.map(function (result) {
delete result.age;
delete result.phone;
});
console.log(result)

How to relate two (or more) objects through a property (in javascript)?

Let's say I have these two objects:
let person1 = {name: "Charlie", age: 65, childrenNames:["Ruth", "Charlie Jr."] parentNames: ["Dolph", "Grace"]};
let person2 = {name: "Charlie Jr.", age: 34, childrenNames:[] parentNames: ["Charlie", "Grace"]};
Now let's say I want to express the fact that person1 is person2's father and, consequently, that person2 is person1's son. That is, the "Charlie Jr" in the person1's childrenNames property is person2 and the "Charlie" in the person2's parentNames property is person1.
How could I achieve this? I don't see how embedding one object inside the other would solve the problem, but simply replicate it. Is there a way to make a property inside an object a sort of identifier for another object?
Thanks so much!
For example if you want to know if someone is the child of person 1, you can do something like this:
person1.childrenNames.forEach((childrenName) => {
if(childrenName=== person2.name) {
console.log(person1.name + ' is the parent of + person2.name);
});
Also you can do a nested function so you can check if the person if the parent of multiple persons.
Why not add relationship indexes ? combine your people, to 1 people array.
Iterate and add instead of parentNames, parentIndexes. This way, instead of looking for parents or sons by names, you have the index.
Note, to make my example simple, I am only doing parent to son relationship. You can easily add a son to parent relationship using the exact same logic.
Example
if (peopleArray[i].parentsIndex.length > 0) {
// get first parent
//peopleArray[peopleArray[i].parentsIndex[0]];
}
Modify your object.
let peopleArray = [
{
name: "Charlie",
age: 65,
parentNames: ["Dolph", "Grace"]
},
{
name: "Grace",
age: 65,
parentNames: ["Dolph", "Grace"]
},
{
name: "Dolph",
age: 65,
parentNames: ["ADSGS", "Grace"]
}
];
peopleArray = peopleArray.map(callback.bind(null));
function callback(item) {
item["parentsIndex"] = [];
for (let i = 0; i < item.parentNames.length; i++) {
let parentObj = peopleArray.find(x => x.name === item.parentNames[i]);
if (parentObj !== undefined) {
item["parentsIndex"].push(peopleArray.indexOf(parentObj));
}
}
return item;
}
console.log(peopleArray);
// use case
if (peopleArray[0].parentsIndex.length > 0) {
// get first parent
//peopleArray[peopleArray[0].parentsIndex[0]];
}
I guess it depends on how complicated your scenario would be and what you would like to achieve, but say you add an extra table for relations. This table could hold information on the type of relation 2 persons share, and could then be used to look up that data.
For example, if we have 4 persons, from which 2 are parents (Charlie & Grace) and 1 is the son (Charlie Jr), we could form a relation table as below.
We don't need to indicate that Charlie Jr is a son, as he we already know the parents of the child.
const familyDb = {
persons: [
{ id: 1, name: 'Charlie', age: 68 },
{ id: 2, name: 'Grace', age: 64 },
{ id: 3, name: 'Charlie Jr', age: 34 },
{ id: 4, name: 'Grace', age: 36 }
],
relations: [
{ id: 1, person1: 1, person2: 2, type: 'spouse', from: 1970, till: null },
{ id: 2, person1: 3, person2: 4, type: 'spouse', from: 2010, till: null },
{ id: 3, person1: 1, person2: 3, type: 'parent' },
{ id: 3, person1: 2, person2: 3, type: 'parent' }
]
};
function getParents( person ) {
return familyDb.relations.filter( relation => relation.person2 === person.id && relation.type === 'parent' );
}
function getChildren( person ) {
return familyDb.relations.filter( relation => relation.person1 === person.id && relation.type === 'parent' );
}
console.log( getParents( familyDb.persons[2] ) );
console.log( getChildren( familyDb.persons[0] ) );
So the above code kinda takes a rudimentary approach to this, you have:
a unique id identifying a person (name matching would be hard in your example as Grace is both the mom of Charlie & Charlie Jr)
a table identifying a relation of some type between two persons
After that you just need a way to look up the information from your dataset and you have a way to get started

How to match mongo document against an array of rules one by one

I do a find and get a single document back. I also have a set of mongo rules. I need to match the document against this set of rules and if the document matches a rule, append the name of the rule to a rule-name subdocument.
Assume the document is this -
var randomGuy = { name: "Random Guy", age: 45, state: "assam", profession: "coder", ruleNames: [] };
I have that stored in a JavaScript variable. I also have a set of rules, converted to mongodb rules -
var rules = [
{'rule1': { name: /R*/i, age: { $gt: 40 } }},
{'rule2': { state: "karnataka" }},
{'rule3': { age: { $lt: 60 } }},
{'rule4': { $or: [ { profession: 'coder' }, { profession: 'programmer' } ] }}
];
I want to loop over the rules, match the randomGuy object against each and append the rule names to the randomGuy's ruleNames property. So the final randomGuy object looks like this -
var randomGuy = { name: "Random Guy", age: 45, state: "assam", profession: "coder", ruleNames: ['rule1', 'rule3', 'rule4'] };
I think i found the answer in sift.js - https://github.com/crcn/sift.js
All i will need to do is apply the rules as sift filters on the randomGuy object.
var randomGuys = [randomGuy];
var ruleName, ruleString;
rules.forEach(function(rule) {
ruleName = Object.keys(rule)[0];
ruleString = rule[ruleName];
if(sift(ruleString).test(randomGuy)) {
randomGuys.ruleNames.push(ruleName);
}
}

Categories

Resources