How do you check if value exist in object of object's array? - javascript

I want to know which logic i should use to check every object's array of parent object contained in grand parent object
Hi guys i want to check if this value for example : "127.0.0.1" exists in this object (MyObject has like 2k objects in it)
{
"name" : MyObject
"value": [
{
"name" : "Object1",
"properties":{
"address" : [
"13.65.25.19/32",
"13.66.60.119/32",
]
}
},
{
"name" : "Object2",
"properties":{
"address" : [
"13.65.25.19/32",
"127.0.0.1",
]
}
}
]
}
Btw does include() needs to match the whole string or for example if 127.0.0.1 is like this in my object 127.0.0.1/32, i can still retrieve it even if there is a ip range ?

Your data is structured quite specifically, so you can write a custom method which you can call over and over again. It will check for a
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const includesAddress = (address) => {
for (const val of obj.value) {
if (val.properties.address.some((a) => address === a)) return true;
}
return false;
};
console.log(includesAddress(address));

Array.flatMap implementation
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '127.0.0.1';
const output = obj.value.flatMap(item => item.properties.address).includes(address);
console.log(output);
If you want check if the partial ip addess is included in the list, you should make use of a regex implementation.
Sample Implementation
const obj = {
name: 'MyObject',
value: [
{
name: 'Object1',
properties: {
address: ['13.65.25.19/32', '13.66.60.119/32'],
},
},
{
name: 'Object2',
properties: {
address: ['13.65.25.19/32', '127.0.0.1'],
},
},
],
};
const address = '13.65.25.19';
const regex = new RegExp(address, 'i')
const output = obj.value.flatMap(item => item.properties.address).filter(x => regex.test(x)).length > 0;
console.log(output);

Related

Search query String Array Object in mongoose and use elemMatch is not working as expected

I am facing with an error which I am unable to resolve it.
I want to use query search to search if the data of 1 job matches with user data but I am stucked in some cases.
First case it is that my query search of the job looks like this I mean the data.
The problem it is that in the searchFilterSkills.searchSkillsOffer I have an array of objects and I want to match the name of each of them if one of them exist but I am unable to iterate through them because I get an array of Strings with .map() which cannot iterate on it.
After answer from Fabian if all elements matches it returns the elements and it matches but I want if 1 of the elements matches it will return the object.
I tried $in but did not work. Is there any query to use instead of $all
These are my data which I try to search.
"skillsOffer":[
{
"name":"Max",
"rate":0
},
{
"name":"Test",
"rate":0
},
{
"name":"Javascript",
"rate":0
}
],
"country":"DEU",
"postalCode":12345
And these are the user Data which he/she has.
"searchFilter" : {
"remote" : 0,
"data" : [
{
"region" : [
"1"
],
"country" : "DEU",
"searchActive" : false,
"postalCode" : "123",
"available" : {
"$date" : 1664955924380
}
}
]
},
"searchFilterSkills" : {
"searchSkillsOffer" : [
{
"name" : "Javascript",
"rate" : 100
},
{
"name" : "Test",
"rate" : 60
},
{
"name" : "Client",
"rate" : 0
}
],
}
At skillsOffer I want to search if only the name matches not the rate.
Then if remote is 1 then search the above query and without postalCode with remote or the above one and remote.
async searchUsers(req, res, next) {
const jobID = req.query.jobID;
let job = await Job.findById(jobID);
let postalCode = job.postalCode;
postalCode = postalCode.toString().slice(0, 1);
let postalCode2 = job.postalCode;
postalCode2 = postalCode2.toString().slice(0, 2);
let postalCode3 = job.postalCode;
postalCode3 = postalCode3.toString().slice(0, 3);
let postalCode4 = job.postalCode;
postalCode4 = postalCode4.toString().slice(0, 4);
let postalCode5 = job.postalCode;
postalCode5 = postalCode5.toString().slice(0, 0);
let userIds = job.skillsOffer.map(user => user.name).join(",");
let users = await User.find({
"searchFilter.data": {
$elemMatch: {
"$or": [
{
postalCode: postalCode,
},
{
postalCode: postalCode2,
},
{
postalCode: postalCode3,
},
{
postalCode: postalCode4,
},
{
postalCode: postalCode,
},
{
postalCode: postalCode5,
},
]
}
},
"searchFilter.data": {
$elemMatch: {
country: job.country
}
},
'searchFilterSkills.searchSkillsOffer': {
$elemMatch: {
name: {
$regex: new RegExp(`^${job.skillsOffer.map(jt => jt.name)}`, 'i'), but it does not return a thing here
},
},
},
});
if (job.remote.toString() === "1") {
users = await User.find({
"searchFilter.data": {
$elemMatch: {
"$or": [
{
postalCode: postalCode,
},
{
postalCode: postalCode2,
},
{
postalCode: postalCode3,
},
{
postalCode: postalCode4,
},
{
postalCode: postalCode,
},
{
postalCode: postalCode5,
},
]
}
},
"searchFilter.data": {
$elemMatch: {
country: job.country
}
},
"searchFilter.remote": job.remote,
});
}
if (!users) {
res.status(204).json({ error: "No Data" });
return;
}
return res.status(200).send({
user: users.map(t =>
t._id
)
});
},
I assume you want to match each name from skillsOffer array. This way you have to define an $elemMatch object for each name (basically mapping each name).
You can use the following (partial) query in your code in order to check whether all names are contained in your searchFilterSkills.searchSkillsOffer array.
{
'searchFilterSkills.searchSkillsOffer': {
$all: job.skillsOffer
.map((user) => user.name)
.map((name) => ({
$elemMatch: {
name: {
$regex: new RegExp(`^${name}$`, 'i'),
},
},
})),
},
}
If you would like to match any name, you should or the following code:
{
$or: job.skillsOffer
.map((user) => user.name)
.map((name) => ({
'searchFilterSkills.searchSkillsOffer': {
$elemMatch: {
name: {
$regex: new RegExp(`^${name}$`, 'i'),
},
},
},
})),
}

Returning an array of all the pet names

If I were to create a function, were a persons name was entered, how would I return an array with the names of the pets from the object below, what would be the best method if I were to use a for loop to iterate over it? I've not quite learnt some of the ES6 features yet and i'm new to coding.
A typical array of owners is shown below:
[
{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
},
{
name: 'Caroline',
pets: ['Basil', 'Hamish'],
},
];
Thanks for the fast replies! :)
It's pretty simple to achieve it:
you search for the corresponding owner with the find function, then, if you have an owner, you return the pets key, which is already an array according to the code provided. If you have no owner corresponding to the name entered, then you'll get "undefined", but you can customise this code to have an empty array if it better fits your needs.
const data = [{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
}, {
name: 'Caroline',
pets: ['Basil', 'Hamish'],
}, ];
const getPetsByOwnerName = (ownerName) => {
const owner = data.find(d => d.name === ownerName);
return owner ? owner.pets : undefined;
}
const carolinePets = getPetsByOwnerName('Caroline');
console.log(carolinePets);
EDIT: author request to do it with a loop
const data = [{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
}, {
name: 'Caroline',
pets: ['Basil', 'Hamish'],
}, ];
function getPetsByOwnerNameWithLoop(ownerName) {
for (let i = 0; i < data.length; i++) {
if (data[i].name === ownerName) {
return data[i].pets;
}
}
return undefined;
}
const carolinePets = getPetsByOwnerNameWithLoop('Caroline');
console.log(carolinePets);
let ownersArray = [ { name: 'Malcolm', pets: ['Bear', 'Minu'], }, { name: 'Caroline', pets: ['Basil', 'Hamish'], }, ];
const petArray = (owner, ownersArray) => {
let array = ownersArray.filter((arr) => arr.name===owner)
return array.length>0 ? array[0].pets : 'owner not found'
}
console.log(petArray("Caroline", ownersArray))
Try filter() method. The function returns an array of names from the filtered owner as a result.
Example code:
const arr = [
{ name: 'Malcolm', pets: ['Bear', 'Minu'], },
{ name: 'Caroline', pets: ['Basil', 'Hamish'], }
];
function petsNames(val) {
return arr.filter(x => x.name === val)[0].pets;
};
console.log(petsNames('Malcolm'));

Converting an array to an object of nested objects for a tree diagram in Javascript

i'm attempting to create a Tree Diagram with react-d3-js. It needs to be in a specific format. So i need to convert the initial data that i have to the format.
This is a diagram for a shop to see the distribution chain and who is allowed to make a purchase from specific nodes.
Initial Data:
store.name = 'Absolut Chocolat' //Main Parent
store.shopconditions: [
{
"role": "agent",
"condition": ["owner", "stokist"]
},
{
"role": "stokist",
"condition": ["owner", "master stokist"]
},
{
"role": "master stokist",
"condition": ["owner"]
}
]
// If role is agent, then they are allowed to buy from 'owner' and 'stokist'
Here's the hardcoded ideal output:
orgChart = {
name: 'Absolut Chocolat',
children: [
{ name: 'Agent' },
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
{
name: 'Master Stokist',
children: [
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
],
},
],
};
With a few for each loops, i've gotten to the first 2 layers of the intended output but i cannot find a way to get more than that.
Here is what i got so far:
Agent node is not under Master Stokist
Current code:
let chartData = { name: store.name, children: [] };
store.shopconditions.forEach((i) => {
i.condition.forEach((c) => {
if (c === 'owner') {
chartData.children.push({ name: i.role });
}
});
});
const chartDataParser = (data) => {
data.children.map((i) => {
for (const [k, v] of Object.entries(i)) {
store.shopconditions.forEach((c) => {
c.condition.forEach((o) => {
if (o === v) {
if (!i.children) {
i.children = [{ name: c.role }];
} else {
i.children.push({ name: c.role });
}
}
});
});
}
});
};
chartDataParser(chartData);
Current output:
{
name: 'Absolut Chocolat',
children: [
{ name: 'Agent' },
{
name: 'Stokist',
children: [
{
name: 'Agent',
},
],
},
{
name: 'Master Stokist',
children: [
{
name: 'Stokist',
// Missing children: Agent Node
},
],
},
],
};
What the tree diagram should look like:
As you can see under Master Stokist node, Agent is under Stokist
The Agent node is not reached under the stokist node in the right most chain. I need a fix to my current code so it can go to that extra layer. Thanks in advance. Looking forward to learn from your answers.
You can build an object that lists children by role and then use that to recursively build the nodes of the object. Possibly something like the following:
const store = {
name: 'Absolut Chocolat',
shopconditions: [
{ "role": "agent", "condition": ["owner", "stokist"], name: 'Agent' },
{ "role": "stokist", "condition": ["owner", "master stokist"], name: 'Stockist' },
{ "role": "master stokist", "condition": ["owner"], name: 'Master Stockist' },
]
};
const build_role_map = (store) => {
let role_map = Object.fromEntries(
store.shopconditions.map((v) => [v.role, { ...v, children: [] }])
);
role_map.owner = { "role": "owner", "condition": [], children: [], name: store.name };
store.shopconditions.forEach(
({ role, condition }) => {
condition.forEach((parent) => { role_map[parent].children.push(role) })
}
);
return role_map;
};
const build_node = (role_map, { name, children }) => {
let node = { name };
if(children.length > 0)
node.children = children.map((child) => build_node(role_map, role_map[child]));
return node;
};
const build_tree = (store) => {
const role_map = build_role_map(store);
return build_node(role_map, role_map.owner);
};
console.log(build_tree(store));

Updated nested object by matching ID

I have an array with nested objects that I need to update from another array of objects, if they match.
Here is the data structure I want to update:
const invoices = {
BatchItemRequest: [
{
bId: "bid10",
Invoice: {
Line: [
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "10110" },
},
},
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "11110" },
},
Amount: 2499,
},
],
},
},
{
bId: "bid10",
Invoice: {
Line: [
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "10110" },
},
},
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "10111" },
},
Amount: 2499,
},
],
},
},
],
};
Here is the array of objects I want to update it from:
const accounts = [
{ AccountCode: "10110", Id: "84" },
{ AccountCode: "11110", Id: "5" },
{ AccountCode: "10111", Id: "81" },
];
I want to update invoices, using accounts, by inserting Id if AccountCode matches, to get the following structure:
const invoices = {
BatchItemRequest: [
{
bId: "bid10",
Invoice: {
Line: [
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "10110", Id: "84" },
},
},
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "11110", Id: "5" },
},
Amount: 2499,
},
],
},
},
{
bId: "bid10",
Invoice: {
Line: [
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "10110", Id: "84" },
},
},
{
SalesItemLineDetail: {
ItemAccountRef: { AccountCode: "10111", Id: "81" },
},
Amount: 2499,
},
],
},
},
],
};
I have tried various methods, such as the following:
const mapped = invoices.BatchItemRequest.map((item1) => {
return Object.assign(
item1,
accounts.find((item2) => {
return item2 && item1.Invoice.Line.ItemAccountRef.AccountCode === item2.AccountCode;
})
);
});
Problem with this approach (it doesn't work as I think I need to do another nested map), but it also creates a new array, only including the nested elements of invoices.
Does anyone know a good approach to this?
This isn't the cleanest of code but it gets the job done:
function matchInvoiceWithAccount(invoices, accounts) {
const mappedInvoices = invoices.BatchItemRequest.map((request) => {
// Shouldn't modify input parameter, could use Object.assign to create a copy and modify the copy instead for purity
request.Invoice.Line = request.Invoice.Line.map((line) => {
const accountCode = line.SalesItemLineDetail.ItemAccountRef.AccountCode;
// If accounts was a map of AccountCode to Id you would't need to search for it which would be more effective
const account = accounts.find((account) => account.AccountCode === accountCode);
if (account) {
line.SalesItemLineDetail.ItemAccountRef.Id = account.Id;
}
return line;
});
return request;
});
return {
BatchItemRequest: mappedInvoices,
};
}
What you could and probably should do to improve this is to not modify the input parameters of the function, but that requires that you in a better way copy the original, either using Object.assign or spread operator.
At first, it will be good to create Map from your accounts array. We will go one time for array with O(n) and then will read ids by code with O(1). And nested fors is O(m*n), that will be much more slower at big arrays.
const idsByAccountCodes = new Map();
accounts.forEach((data) => {
idsByAccountCodes.set(data.AccountCode, data.Id);
})
or shorter:
const idsByAccountCode = new Map(accounts.map((data) => [data.AccountCode, data.Id]))
then if you want to mutate original values you can go through all nesting levels and add values
for ( const {Invoice:{ Line: line }} of invoices.BatchItemRequest){
for ( const {SalesItemLineDetail: {ItemAccountRef: item}} of line){
item.Id = idsByAccountCodes.get(item.AccountCode) || 'some default value'
// also if you don't have ids for all codes you need to define logic for that case
}
}
If you don't need to mutate original big object "invoices" and all of nested objects, then you can create recursive clone of if with something like lodash.cloneDeep

Converting an array of objects into an object of objects

Recently, I've been learning on how to retrieve objects from an array and I've had my fair share of converting an array of objects into a singular object of objects, but I couldn't wrap my head around this one!
dataOfCars.js:
const dataOfCars = [
{
id: "car1",
owner: { license: "license001", name: "driver1" },
mechanic: [
{
id: "mechanic1",
owner: { license: "license001", name: "driver2" }
}
]
},
{
id: "car2",
owner: { license: "license021", name: "driver2" },
mechanic: []
},
{
id: "car3",
owner: { license: "license002", name: "driver2" },
mechanic: [
{
id: "mechanic1",
owner: { license: "license002", name: "driver2" }
}
]
}
];
module.exports = dataOfCars;
I know there are several examples in regards to this but the output I'm expecting is quite different as it involves nested objects:
{
cars : {
idOrder : {
"car1" : {
id : "car1",
owner : "owner1",
mechanic : ["mechanic1", "mechanic2"]
},
...
},
result : ["car1", "car2", ...]
},
mechanics : {
idOrder : {
"mechanic1" : {
id : "mechanic1",
owner : "driver2",
},
...
},
result : ["mechanic1", ...]
},
owners : {
idOrder : {
"driver1" : {
license : "license001",
name: "driver1",
},
...
},
result : ["driver1", "driver2", ...]
}
}
I gave it a go at Sandbox: https://codesandbox.io/s/old-morning-hx9m1. I used Object.assign({}, ...dataOfCars) but it only 'spreads' the whole array, thus returning the final element only per entity. Here's the code at index.js:
import dataOfCars from "./data.js";
import { normalize, schema } from "normalizr";
const ownerSchema = new schema.Entity("owners");
const mechanicSchema = new schema.Entity("mechanics", {
mechanic: ownerSchema
});
const carSchema = new schema.Entity("cars", {
owner: ownerSchema,
mechanics: [mechanicSchema]
});
/* This method somehow returns the very final element */
const objectPost = Object.assign({}, ...dataOfCars);
const normalizedPost = normalize(objectPost, carSchema);
// The normalized object returning the 2/3 expected entities
console.log(normalizedPost);
I'm still relatively new to ES6 and I would love to know how this works out in the end! Thanks for the help in advance!

Categories

Resources