Get accessed to plucked object using javascript and lodash - javascript

I have an array of users in my javascript. For each user I am comparing if that user appears in another list.
var users = USERS.getUsers();
for (var i = 0; i < users.length; i++) {
var u = users[i];
if (util.pluck(myList.adminUsers, 'email').includes(u.email)) {
// How do I check the value of the plucked value for myList.adminUsers.locationId ?
u.status = "admin";
}
}
users is an array of user objects.
[{...}]
0:
id: "1"
email: "johndoe#gmail.com"
firstname: "John"
lastname: "Doe"
roleid: "1"
_proto__: Object
1:
id: "2"
email: "janedoe#gmail.com"
firstname: "Jane"
lastname: "Doe"
roleid: "1"
_proto__: Object
myList.adminUsers is also an array of user objects but also with locationId.
[{...}]
0:
id: "1"
email: "johndoe#gmail.com"
firstname: "John"
lastname: "Doe"
roleid: "1"
locationId: "123"
_proto__: Object
I need to compare another field in this check. So I need to see if the plucked object from myList.adminUsers has a field locationId that equals x, but I'm not sure how to do this?
How can I get access to the plucked object so I can check the value of locationId?

Use findWhere instead of pluck. You can give it an object containing all the properties you want to match.
if (util.findWhere(myList.adminUsers, {email: u.email, locationId: u.locationId})) {
u.status = "admin";
}

This should give you the list of admins that are found in the list of users and are in the location ID you provide as a value (I set it as a variable).
const users = [
{
id: "1",
email: "johndoe#gmail.com",
firstname: "John",
lastname: "Doe",
roleid: "1"
},
{
id: "2",
email: "janedoe#gmail.com",
firstname: "Jane",
lastname: "Doe",
roleid: "1"
}
];
const admins = [
{
id: "1",
email: "johndoe#gmail.com",
firstname: "John",
lastname: "Doe",
roleid: "1",
locationId: "123"
}
];
const locationIdToFind = '123';
const adminsWithLocation = _.intersectionWith(admins, users, (admin, user) => _.isEqual(admin.email, user.email) && _.isEqual(admin.locationId, locationIdToFind));
console.log(adminsWithLocation);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>

Related

How to filter and checked matches conditionally with multiple fields

How to filter and checked matches conditionally with multiple fields passing in string;
i have a request as like below:
{
name: "abc",
email: "",
phone: "123456",
match: "phone"
}
In that case i have to filtered array and get match phone objects in response and
i have an array as like below
[{name: "abc", email: "abc#gmail.com",phone:"123456"}, {name: "abc", email: "abc#gmail.com", phone:"1236"}, {name: "pqr", email: "pqr#gmail.com", phone:"123456"} ]
in that case my expected output as like below
[{name: "abc", email: "abc#gmail.com",phone:"123456"}, {name: "pqr", email: "abc#gmail.com", phone:"123456"} ]
Note: my filter condition would be change as per the match string it could be on
1st request type
{
email: "pqr#gmail.com",
phone: "123456",
match: "phone,email"
}
Result:
[{name: "pqr", email: "pqr#gmail.com", phone:"123456"}]
2nd request type
{
name: "abc",
email: "abc#gmail.com",
phone: "1236",
match: "phone,email"
}
Result:
[ {name: "abc", email: "abc#gmail.com", phone:"1236"}]
name,phone or phone or email or name,email,phone or name only
in that case i have to manipulate filter based on match string
Even though I don't understand 100% of your question, I believe that the code below can help you.
const data = [
{name: "abc", email: "abc#gmail.com",phone:"123456"},
{name: "abc", email: "abc#gmail.com", phone:"1236"},
{name: "pqr", email: "pqr#gmail.com", phone:"123456"}
]
const options = {
name: "abc",
email: "",
phone: "123456",
match: "phone"
}
function filter(data,options){
const keys = options.match.split(',')
return data
.filter(item=>{
return keys
.map(key=>item[key] === options[key])
.every(check => check)
})
}
const test = filter(data,options)
console.log(test)
You can define a function, filterArr(arr, cond) that can be used to test every condition on the fields specified by condition.match property as follows:
const
input = [{name: "abc", email: "abc#gmail.com",phone:"123456"}, {name: "abc", email: "abc#gmail.com", phone:"1236"}, {name: "pqr", email: "pqr#gmail.com", phone:"123456"} ],
cond1 = {name: "abc", email: "", phone: "123456", match: "phone"},
cond2 = {email: "pqr#gmail.com", phone: "123456", match: "phone,email"},
filterArr = (arr, cond) => arr.filter(item => cond.match.split(',').every(c => cond[c] === item[c])),
output1 = filterArr(input,cond1),
output2 = filterArr(input,cond2);
console.log( output1 );
console.log( output2 );
As per my understanding you want to filter out the objects from an array based on the filterObject properties available in the match property of the filter object.
If my understanding is correct, You can achieve this with the help of Array.filter() method along with the Array.every()
Live Demo :
const arr = [
{name: "abc", email: "abc#gmail.com", phone:"123456"},
{name: "abc", email: "abc#gmail.com", phone:"1236"},
{name: "pqr", email: "pqr#gmail.com", phone:"123456"}
];
const filterObj = {
email: "pqr#gmail.com",
phone: "123456",
match: "phone,email"
};
const matchFilterFields = filterObj.match.split(',');
const res = arr.filter(obj => {
return matchFilterFields.every(field => filterObj[field] === obj[field])
});
console.log(res);

Create New Object key value pair base on array value

I need to generate csv for my client data but I need to include all headers came from my models.
The problem is some of my old client data has no existing fields. I want to create a new object with all the headers as a key and leave some empty string if a client has no data or no existing fields. Thanks for helping!
Here example of headers as key
let header = ["firstname", "lastname", "age", "gender", "address"];
Example for client info
let userInfo = [
{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
},
{
firstname: "Jane",
lastname: "Doe",
},
];
Expected Output
let userInfo = [
{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
address: "",
},
{
firstname: "Jane",
lastname: "Doe",
age: "",
gender: "",
address: "",
},
];
you can create an empty object with array.reduce
const emptyObj = header.reduce((acc, key) => {
acc[key] = "";
return acc;
}, {});
and use array.map on userInfo to return an object that concat the empty object with the one with value
let header = ["firstname", "lastname", "age", "gender", "address"];
let userInfo = [{
firstname: "John",
lastname: "Doe",
age: "20",
gender: "male",
},
{
firstname: "Jane",
lastname: "Doe",
},
];
const emptyObj = header.reduce((acc, key) => {
acc[key] = "";
return acc;
}, {});
const result = userInfo.map(user => {
return {
...emptyObj,
...user
};
})
console.log(result);

javascript function to get list of objects and return new key with new value in new array

for privacy I explain simple example . function that get personal list and return new key with new
value like below:
personalList = [{
firstName: "elena",
lastName: "zakharova"
},
{
firstName: "alex",
lastName: "farmanda"
},
{
firstName: "mike",
lastName: "kenan"
}]
output should be like this:
desiredList =[{fullname :'elena zakhrova'},{fullname :'alex farmanda'}, fullname : 'mike kenan']
tried some ways but unfortunately did not get answer
Any solutions would be appreciated.
You can use map
const personalList = [{
firstName: "elena",
lastName: "zakharova"
},
{
firstName: "alex",
lastName: "farmanda"
},
{
firstName: "mike",
lastName: "kenan"
}]
console.log(personalList.map(({firstName,lastName}) => ({fullName: `${firstName} ${lastName}`})))
Here's How I Would Solve This Using For Loop. You Can Also Use Maps Like How #R4ncid Has Explained
var desiredlist = []
var personalList = [{
firstName: "elena",
lastName: "zakharova"
},
{
firstName: "alex",
lastName: "farmanda"
},
{
firstName: "mike",
lastName: "kenan"
}]
for (i=0;i<personalList.length;i++){
desiredlist.push({"fullname":personalList[i].firstName + " " + personalList[i].lastName})}
console.log(desiredlist)

Best way to replace item in object?

I will fetch this data, the data is always diffrent. Sometimes admin exist sometimes not.
What is the best way to remove all the values in admin and add new value, if admin key exist?
const apiFetched = [{
persons: {
firstName: "John",
lastName: "Doe",
},
admin: {
firstName: "Jeff",
lastName: "Pan",
}
}]
If admin key exist I would like to replace everything in admin and add these:
{ firstName: "Alan", lastName: "Jack" }
like this:
const apiFetched = [{
persons: {
firstName: "John",
lastName: "Doe",
},
admin: {
firstName: "Alan",
lastName: "Jack",
},
}];
iterate the array via forEach
for each item which features an own admin property ...
assign to this item's admin property/object another object like superUser which can feature equally named and/or additional properties ...
in the 1st case, key-value pairs will be replaced/overwritten,
in the 2nd case the admin object would aggregate/accumulate new entries.
const apiFetched = [{
persons: {
firstName: "John",
lastName: "Doe",
},
admin: {
firstName: "Jeff",
lastName: "Pan",
},
}];
const superUser = { firstName: "Alan", lastName: "Jack" };
apiFetched
.forEach(item => {
if (item.hasOwnProperty('admin')) {
Object.assign(item.admin, superUser);
}
});
console.log({ apiFetched });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Here you go:
const apiFetched = [{
persons: {
firstName: "John",
lastName: "Doe",
},
admin: {
firstName: "Jeff",
lastName: "Pan",
}
}]
apiFetched.forEach(i => {
if (i.admin) {
i.admin = {
firstname: "Alan",
lastname: "Jack"
}
}
})
console.log(apiFetched)

javascript count objects in array of objects without null values

Let's say we have array of objects:
const data = [
{
firstName: "Bruce",
lastName: "Wayne",
address: "Arkham 6",
id: "1",
},
{
firstName: "Peter",
lastName: "Parker",
address: "LA 54",
id: "2"
},
{
firstName: "Tony",
lastName: "Stark",
address: null,
id: "3"
}
];
and want to get length of the array but exclude counting of the objects which has null values (in example above, this is the last object with address property null) so that result of the counting of the example above would be 2.
objectsWithoutNull = data.reduce(function (r, a) {
return r + +( a!== null);
}, 0);
I'm trying with reduce method, but got 0.
Where is the problem in iteration?
You can filter() the array and than get object values and check where not includes null.
const data = [
{
firstName: "Bruce",
lastName: "Wayne",
address: "Arkham 6",
id: "1",
},
{
firstName: "Peter",
lastName: "Parker",
address: "LA 54",
id: "2"
},
{
firstName: "Tony",
lastName: "Stark",
address: null,
id: "3"
}
];
const notNullable = data.filter(obj=>!Object.values(obj).includes(null));
console.log(notNullable)
console.log(notNullable.length)
More about Object Values Filter Includes
Reduce the array, for each object get the values with Object.values(), and check with Array.includes() if it contains a null value. Negate with ! the boolean result of inclues, and use the + operator to convert to number. Add the number to the accumulator.
const data = [{"firstName":"Bruce","lastName":"Wayne","address":"Arkham 6","id":"1"},{"firstName":"Peter","lastName":"Parker","address":"LA 54","id":"2"},{"firstName":"Tony","lastName":"Stark","address":null,"id":"3"}];
const result = data.reduce((r, o) =>
r + +!Object.values(o).includes(null)
, 0);
console.log(result);
An option is to iterate over the object-values of a and test if the value is equal to null. If we found a null don't increase our counter.
const data = [
{
firstName: "Bruce",
lastName: "Wayne",
address: "Arkham 6",
id: "1",
},
{
firstName: "Peter",
lastName: "Parker",
address: "LA 54",
id: "2"
},
{
firstName: "Tony",
lastName: "Stark",
address: null,
id: "3"
}
];
let objectsWithoutNull = data.reduce(function (r, a) {
let hasNull = false;
const values = Object.values(a);
values.map(v => {
if (v === null) {
hasNull = true;
}
});
return r + !hasNull;
}, 0);
console.log(objectsWithoutNull);
objectsWithoutNull = data.reduce(function (r, a) {
return r + +( Object.values(a).indexOf(null) == -1);
}, 0);
This will work if you want to check for all the properties!
You can use Array.prototype.every to check that all the values are not null
var length = data.filter(i => Object.values(i).every(i => i !== null)).length
If you are using lodash.
const data = [
{
firstName: "Bruce",
lastName: "Wayne",
address: "Arkham 6",
id: "1",
},
{
firstName: "Peter",
lastName: "Parker",
address: "LA 54",
id: "2"
},
{
firstName: "Tony",
lastName: "Stark",
address: null,
id: "3"
}
];
const counter = _.filter(data, ({address}) => {return address != null}).length;
console.log(counter);

Categories

Resources