I have two arrays and first array are having keys and want to check that all keys are having second array with value true. and return that true value array.
i have code as like below
const keysArray = ['phoneNo', 'name']
const data = [{ demo1:'abc', match_status:{ phoneNo: true, name: null }}, { demo2:'abc', match_status_flag:{ phoneNo: true, name: true }}]
My expected output as like below:
const outputArray = [{ demo2:'abc', match_status_flag:{ phoneNo: true, name: true }}]
i tried code as like below but not getting expected output
keysArray.map((k) => data.filter(i => i.match_status[k] === true))
You need a common property, like match_status_flag and filter the data.
const
keys = ['phoneNo', 'name'],
data = [{ demo1: 'abc', match_status_flag: { phoneNo: true, name: null } }, { demo2: 'abc', match_status_flag: { phoneNo: true, name: true } }],
result = data.filter(({ match_status_flag }) =>
keys.every(k => match_status_flag[k])
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I have 2 arrays, one (array1) which needs to be sorted based on its inner key, role, according to another (array2). I have tried different solutions but cannot progress any further since i don't understand what steps i should take
I have the following output: Array1
{
"id":12,
"roles":[
{
"id":12,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"LWB"
}
}
}
],
"user_email":"w#w.w"
},
{
"id":1575,
"roles":[
{
"id":1672,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"LB"
}
}
}
],
"user_email":"j#j.s"
},
{
"id":1576,
"roles":[
{
"id":1673,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"CAM"
}
}
}
],
"user_email":"E#E.E",
},
And i want to order the array above according to the order of this:
const array2 = ["LWB", "LB", "CAM"]
The issue i'm having is that the given key that the sorting should be according to in array1 is too deep, and I haven't found any way to map the "role" from the first array with the array2.
You need to get role and with this value get the index for the order.
const
getRole = ({ roles: [{ team_meta: { default_player_role: { role } }}] }) => role,
data = [{ id: 1576, roles: [{ id: 1673, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "CAM" } } }], user_email: "E#E.E" }, { id: 12, roles: [{ id: 12, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LWB" } } }], user_email: "w#w.w" }, { id: 1575, roles: [{ id: 1672, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LB" } } }], user_email: "j#j.s" }],
order = ["LWB", "LB", "CAM"];
data.sort((a, b) => order.indexOf(getRole(a)) - order.indexOf(getRole(b)));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Over several loops you can also sort it but probably not an elegant solution:
const nestedArray = [...]; // Replace Array
const sortByArray = ["LWB", "LB", "CAM"];
const sortedArray = [];
sortByArray.forEach(function(sortByArrayValue) {
nestedArray.forEach(function(nestedArrayValue) {
nestedArrayValue.roles.forEach(function(role) {
if (role.team_meta.default_player_role.role === sortByArrayValue) {
sortedArray.push(nestedArrayValue);
}
});
});
});
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);
Question, I have objects that I want to filter to get a specific value, but the problem is I need to map also a specific key to get all the value that need for my filter.
Sample code
const arr = [{
"invitedPeopleId": [
{
"isAdmin": false,
"isActive": true,
"_id": "6127a0d12a55f41b380482c3",
}
],
"_id": "620be40739797c2064d9e26f",
"projectId": {
"_id": "620914a24d35c13d48c6be2a"
},
"taskCreatorId": {
"isAdmin": true,
"isActive": true,
"_id": "6127a0bb2a55f41b380482c0"
},
"taskName": "Create login page for user registration"
}]
const compare = '6127a0d12a55f41b380482c3';
arr.filter((x) => x.contact.map((y) => y.landline) === compare); // return empty
Thanks!
You could filter by taking contact and ther if some value compares with the wanted one.
const
array = [{ _id: 1234, name: 'john', contact: [{ landline: '321321' }, { mobile: '123131' }] }, { _id: 1234, name: 'jane', contact: [{ landline: '5435353' }, { mobile: '5435353' }] }],
compare = '321321',
result = array.filter(({ contact }) =>
contact.some(({ landline }) => landline === compare)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have a filter object that is returned by query params
url = /all?channels=calls,text&calls=voicemail,missed
const query = {
channels: 'calls,texts',
calls: 'voicemail,missed',
};
I then have an array of objects that come in from a socket.
const arr = [
{
id: 1,
channel: 'SMS',
sent: '2021-08-22T03:21:18.41650+0000',
sender: {
contactType: 'business',
},
recipients: [
{
contactType: 'corporate',
},
],
direction: 'INBOUND',
},
{
id: 2,
channel: 'VOICE',
sent: '2021-08-20T23:15:56.00000+0000',
sender: {
contactType: 'business',
},
recipients: [
{
contactType: 'corporate',
},
],
callDetails: {
answered: false,
voicemail: true,
},
direction: 'INBOUND',
},
{
id: 3,
channel: 'VOICE',
sent: '2021-08-20T23:15:56.00000+0000',
sender: {
contactType: 'business',
},
recipients: [
{
contactType: 'corporate',
},
],
callDetails: {
answered: true,
voicemail: false,
},
direction: 'INBOUND',
},
{
id: 4,
channel: 'VOICE',
sent: '2021-08-20T23:15:56.00000+0000',
sender: {
contactType: 'business',
},
recipients: [
{
contactType: 'corporate',
},
],
callDetails: {
answered: false,
voicemail: false,
},
direction: 'INBOUND',
},
];
I want to filter out the objects that match the filters but the query obj isn't friendly enough to just map the arr through.
With the query obj shared above, i should return the objects id:1 and id:2 and id:4 from arr, since those object meet the criteria of sms, voicemail, & missed
I assume i need a modified query obj that has to have various conditions available for each property, i.e calls: voicemail === callDetails.voicemail === true or calls: received === callDetails.answered === true
I've seen lots of examples on how to filter an array of objects with multiple match-criteria, but with the req of the property having multiple conditions, i've hit a wall.
thanks for the help
The main idea is to provide kind of a rosetta stone which does bridge/map the query specific syntax with any list item's specific data structure. Thus one will end up writing a map which takes a query's structure into account but ensures for each necessary query endpoint an item specific filter condition/function.
The query function should simply filter the item list by applying a list of logical OR conditions, thus using some for returning the boolean filter value.
Which leaves one of implementing a helper method which collects ... via Object.entries and Array.prototype.flatMap as well as via String.prototype.split and Array.prototype.map ... the function endpoints from the above introduced requirements configuration/map, based on the query object, provided by the system. Thus this helper might be named resolveQuery.
const sampleList = [{
id: 1,
channel: 'SMS',
direction: 'INBOUND',
}, {
id: 2,
channel: 'VOICE',
callDetails: {
answered: false,
voicemail: true,
},
direction: 'INBOUND',
}, {
id: 3,
channel: 'VOICE',
callDetails: {
answered: true,
voicemail: false,
},
direction: 'INBOUND',
}, {
id: 4,
channel: 'VOICE',
callDetails: {
answered: false,
voicemail: false,
},
direction: 'INBOUND',
}];
// prepare a `requirements` map which ...
// - on one hand maps `query`-syntax to a list items's structure
// - and on the other hand does so by providing an item specific
// filter condition/function for each necessary query endpoint.
const requirements = {
channels: {
texts: item => item.channel === 'SMS',
},
calls: {
voicemail: item => item.channel === 'VOICE' && !!item.callDetails.voicemail,
missed: item => item.channel === 'VOICE' && !item.callDetails.answered,
},
}
// const query = {
// channels: 'calls,texts',
// calls: 'voicemail,missed',
// };
function resolveQuery(requirements, query) {
const reject = item => false;
// create/collect a list of filter condition/functions
// which later will be applied as logical OR via `some`.
return Object
.entries(query)
.flatMap(([ groupKey, groupValue ]) =>
// e.g groupKey => 'channels',
// groupValue => 'calls,texts'
groupValue
.split(',')
.map(requirementKey =>
// e.g requirementKey => 'calls'
// or requirementKey => 'texts'
requirements?.[groupKey]?.[requirementKey?.trim()] ?? reject
)
);
}
function queryFromItemList(itemList, requirements, query) {
const conditionList = resolveQuery(requirements, query);
console.log(
'conditionList ... [\n ',
conditionList.join(',\n '),
'\n]'
);
return itemList.filter(item =>
conditionList.some(condition => condition(item))
);
}
console.log(
queryFromItemList(sampleList, requirements, {
channels: 'calls,texts',
calls: 'voicemail,missed',
})
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Is there a solution to check in JavaScript if two objects have the same value and then get the value?
Here is some code for demonstration:
An Object in Array 1 (“generalData”):
this.generalData = [
{
specificId: 210001,
name: 'Test 1',
optionsAvaiable: false,
mode: 0,
},
];
An Object in Array 2 (“selectedData”):
this.selectedData = [
{
specificId: 210001,
name: 'Test 1',
optionsAvaiable: false,
column: {
disableHtmlEncode: true,
allowSorting: false,
allowResizing: true,
allowFiltering: false,
allowGrouping: false,
},
foreignKeyData: undefined,
index: '0',
mode: 0,
},
];
I want to get the specific id so the expected output is 210001
My current solution (messy):
this.generalData.forEach((generalDataObj) => {
this.selectedData.forEach((selectedDataObj) => {
if (generalDataObj.specificId == selectedDataObj.specificId) {
console.log(generalDataObj.specificId); // (210001)
}
});
});
Is there a cleaner solution to solve this?
If you only want one result, you can use the find method.
const generalData = [{ specificId: 2345 }, { specificId: 1234 }]
const selectedData = [{ specificId: 1234 }, { specificId: 876 }, { specificId: 675 }]
const result = generalData.find(a => selectedData.find(b => a.specificId === b.specificId))
console.log(result)