I was looking at the docs for lodash. There is a function called "filter", but it is used in a different way than the "filter" from import filter from "lodash/fp/filter";. For example, this code does not work:
import filter from "lodash/fp/filter";
var users = [
{ user: "barney", age: 36, active: true },
{ user: "fred", age: 40, active: false }
];
const newUsers = filter(users, function (o) {
return !o.active;
});
console.log(newUsers);
However, I can't seem to find the cos for "import filter from "lodash/fp/filter";
Lodash/fp function are iteratee (the callback function) first, data last, and curried, so you can create new functions, and then supply the data:
const { filter } = _; // import { filter } fron 'lodash/fp'
const filterActiveUsers = filter(o => !o.active);
const users = [
{ user: "barney", age: 36, active: true },
{ user: "fred", age: 40, active: false }
];
console.log(filterActiveUsers(users));
// which is identical to
console.log(filter(o => !o.active, users));
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
Related
I have a lot of inputs, after which my object is supposed to filter, I can hardcode it, but there is probably a smarter way to do it
Filter state :
const [filters, setFilters] = useState<FiltersType>({
login: "",
name: "",
surrname: "",
});
Example data:
const data: UserRow[] = [
{
key: "1",
login: "John#gmail.com",
name: "John",
surrname: "Smith",
role: ["user"],
},
{
key: "2",
login: "Andrew#gmail.com",
name: "Andrew",
surrname: "Johnson",
role: ["user"],
},
];
data.filter((e) => {
if (
(!filters.name || e.name.includes(filters.name)) &&
(!filters.surrname || e.surrname.includes(filters.surrname)) &&
(!e.login ||
e.login.toLowerCase().includes(filters.login.toLowerCase()))
) {
return true;
}
return false;
})
For example, it can be done like this, but as you can see it looks bad and scales poorly when adding new fields, I tried to simplify it using "Object.entries()", but ultimately failed :(. What is the best pattern for such a problem?
You should use some() (logical OR for all the conditions) or every() (logical AND for all the conditions) in combination with filter().
const data = [
{
key: "1",
login: "John#gmail.com",
name: "John",
surrname: "Smith",
role: ["user"],
},
{
key: "2",
login: "Andrew#gmail.com",
name: "Andrew",
surrname: "Johnson",
role: ["user"],
},
];
const filter = {
login: "",
name: "",
surrname: "",
};
const filters = Object.entries(filter);
const filtered = data.filter((user) =>
filters.some(
([key, value]) =>
user[key] && user[key].toString().toLowerCase().includes(value)
)
);
console.log(filtered);
Use some() if you want to include the result if any of the filter conditions is met and use every() if you want to only include a result if all filter conditions are met.
The above will work for simple filters. You can however extend the solution using typeof() or Array.isArray() function etc. to process different types like arrays, nested objects etc. accordingly.
Just a bit confused as to why this magic method is returning null. It's probably very simple, but I'm using methods I wouldn't normally (bulkingCreating) and can't currently see it.
Association: Country.hasOne(Capital, { foreignKey: 'countryId' });
Populating dummy data:
const countries = await Country.bulkCreate([
{ name: 'England' },
{ name: 'Spain' },
{ name: 'France' },
{ name: 'Canada' }
]);
const capitals = await Capital.bulkCreate([
{ name: 'London' },
{ name: 'Madrid'},
{ name: 'Paris' },
{ name: 'Ottawa' }
]);
countries.forEach((country, index) => {
country.setCapital(capitals[index]);
});
const country = await Country.findOne({where: {name: 'Spain'}});
console.log(country.name, Object.keys(country.__proto__)); // Spain / magic methods
const capital = await country.getCapital();
console.log(capital); // null
The table:
Am I wrong in thinking country.getCapital() should return the relevant entry?
As you might guess setCapital should be an async function because it makes changes in DB so you need to use for instead of forEach method that does not support async callbacks:
let index = 0;
for (const country of countries) {
await country.setCapital(capitals[index]);
index += 1;
}
It would be better to create countries one by one and create capitals for them not relying on the same indexes of both collections (DB might return created records in a different order).
If you are using Sequelize 5.14+, you can do this in 1 bulkCreate using include option.
const countries = await Country.bulkCreate([
{
name: 'England',
Capital: { // This keyname should be matching with model name.
name: 'London'
}
},
{
name: 'Spain',
Capital: {
name: 'Madrid'
}
},
...
],
{
include: Capital,
returning: true // If Postgres, add this if you want the created object to be returned.
}
);
I am currently working with objects and arrays in nodejs in conjuction with filters. I am currenlty facing difficulty in figuring out how to properly traverse an object and filter for the desired results. Instead I am getting undefined. I have an object users and I am wanting to filter for each user configuration that has active === true and then ultimately display every users configuration with that filter in the final result. What is the right/best way to approach this? Should I use map?
Current Result:
undefined
Desired Result:
[
{
email: 'test1#email.com',
active: true
},
{
email: 'test3#email.com',
active: true
},
{
email: 'test4#email.com',
active: true
}
]
Code:
const users = [
{
name: 'User1',
configuration: [
{
email: 'test1#email.com',
active: true
},
{
email: 'test2#email.com',
active: false
}
],
},
{
name: 'User2',
configuration: [
{
email: 'test3#email.com',
active: true
},
{
email: 'test4#email.com',
active: true
}
],
},
];
const result = users.forEach(user => user.configuration.filter( x => {
let {
active
} = x;
return active === true;
}));
console.log(result);
you can use flatMap for this. forEach always returns undefined. usually if you want to return some array use map but since filter also returns an array you need to flat it to get your desired result hence flatMap
const users = [{name: 'User1',configuration: [ {email: 'test1#email.com',active: true},{email: 'test2#email.com',active: false}],},{name: 'User2',configuration: [ {email: 'test3#email.com',active: true},{email: 'test4#email.com',active: true}],},];
const result = users.flatMap(user => user.configuration.filter( x => x.active===true));
console.log(result);
I'm using React.
Raise the child object to the parent.
I want to delete the unnecessary value and send it.
const before = {
address_check: true,
loan_check: true,
oneroom_disable: true,
info: {
age: 13,
name: gogo,
item: [1,2,3]
},
face: {
life: [1,2,3]
}
};
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
const after = {
address_check: true,
age: 13,
name: gogo,
item: [1,2,3]
};
How can I change the status from before to after?
You can create object from other object like below:-
const after = {
address_check: before.address_check,
age: before.info.age,
name: before.info.name,
item: before.info.item
}
You can do something like this:
// Original data
const before = {
address_check: true,
loan_check: true,
oneroom_disable: true,
info: {
age: 13,
name: gogo,
item: [1,2,3]
},
face: {
life: [1,2,3]
}
};
// Destructure required fields
const {address_check, info: {age, name, item}} = before;
// Put them together for your new object
const after = {
address_check, age, name, item
}
I'm trying to create a simple static web page to mess around with some Lodash functions like _.get(). Their docs only specify how to set the _ variable via Node require() syntax. I don't want Node involved for a simple static page.
Putting lodash.core.min.js in a <script> tag isn't allowing me to test _.get(). Is it possible to do this without Node?
UPDATE (solved)
lodash.core does not contain the get() function. (per github.com/lodash/lodash/wiki/Build-Differences)
Using lodash.min.js lets me do what I want. lodash.core.min.js does not.
Use _.noConflict()
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
<script>
_u = _.noConflict();
users = [
{ user: 'barney', age: 36, active: true },
{ user: 'fred', age: 40, active: false },
{ user: 'travis', age: 37, active: true}
];
result = _u.filter(users, function(o) { return o.active; });
console.log(result);
</script>
In https://codepen.io you can simply add lodash as dependency from the quick add. It is a great way to test it:
Also you can use this already prepared pen: test lodash
var users = [
{ user: 'barney', age: 36, active: true },
{ user: 'fred', age: 40, active: false },
{ user: 'travis', age: 37, active: true}
];
result = _.filter(users, function(o) { return o.active; });