const passnegerGroup = [
{ FIRSTNAME: 'RAHUL', LASTNAME: 'KUMAR' },
{ FIRSTNAME: 'RINA', LASTNAME: 'KUMAR' },
{ FIRSTNAME: 'SOHAN', LASTNAME: 'SINGH' },
{ FIRSTNAME: 'PAUL', LASTNAME: 'ANDERSON' },
];
// I want to read each passenger's last name and first name and do some operations.
// Tried this code but this is
for (const key of Object.values(passnegerGroup)) {
console.log(key.FIRSTNAME, key.LASTNAME);
}
output :
RAHUL KUMAR
RINA KUMAR
SOHAN SINGH
PAUL ANDERSON
This is working for but getting ESLINT error.
ESLint: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations. (no-restricted-syntax)
Kindly help me achieve the above using some modern JavaScript/TestCafe codes.
const passnegerGroup = [
{ FIRSTNAME: 'RAHUL', LASTNAME: 'KUMAR' },
{ FIRSTNAME: 'RINA', LASTNAME: 'KUMAR' },
{ FIRSTNAME: 'SOHAN', LASTNAME: 'SINGH' },
{ FIRSTNAME: 'PAUL', LASTNAME: 'ANDERSON' },
];
//No garantee that firstname comes before lastname
const result1 = passnegerGroup.map( u => Object.values(u) ).flat().join(' ');
console.log(result1);
const result2 = passnegerGroup.map( u => [u.FIRSTNAME, u.LASTNAME]).flat().join(' ');
console.log(result2);
const passnegerGroup = [
{ FIRSTNAME: 'RAHUL', LASTNAME: 'KUMAR' },
{ FIRSTNAME: 'RINA', LASTNAME: 'KUMAR' },
{ FIRSTNAME: 'SOHAN', LASTNAME: 'SINGH' },
{ FIRSTNAME: 'PAUL', LASTNAME: 'ANDERSON' },
];
const result = passnegerGroup.reduce((accum, cur) => `${accum} ${cur.FIRSTNAME} ${cur.LASTNAME} `, '');
console.log('result =', result);
Related
Array to be reduced:
const users = [
{ firstname: "Sanket", lastname: "Shevkar", age: 22 },
{ firstname: "Aniket", lastname: "Bhalla", age: 45 },
{ firstname: "Tanvi", lastname: "Shinde", age: 21 },
{ firstname: "Saif", lastname: "Siddiqi", age: 67 },
];
const outout = users.reduce((acc, curr)=>{
if(curr.age<45){
acc.push(curr.firstname);
}
}, [])
Throws TypeError:
Uncaught TypeError: Cannot read property 'push' of undefined
I have passed an empty array to initialize the acc (accumulator), but still it throws typeError. If I return acc at the end, it works perfectly.
const outout = users.reduce((acc, curr)=>{
if(curr.age<45){
acc.push(curr.firstname);
}
return acc;
}, [])
Can someone explain this behaviour?
Array.reduce must return accumulator on every loop
const users = [
{ firstname: "Sanket", lastname: "Shevkar", age: 22 },
{ firstname: "Aniket", lastname: "Bhalla", age: 45 },
{ firstname: "Tanvi", lastname: "Shinde", age: 21 },
{ firstname: "Saif", lastname: "Siddiqi", age: 67 },
];
const outout = users.reduce((acc, curr)=>{
if(curr.age<45){
return acc.concat(curr.firstname);
}
return acc
}, [])
console.log(outout)
I'm trying to write a function to check a deeply nested sub array inside of a complex object to return true if it has values or false if it is empty but I'm not sure how to do this.
The section I'm trying to check is contacts inside each contactGroups section which is where I'm running into issues because the array is nested 4 levels down like object > array of objects > object > contacts array and I'm not sure how to map or iterate at that level.
This is my first pass at a function which is more pseudo code at this point:
const hasContacts = (contacts: {}) => {
if(contacts.contactGroups.length === 0
|| contacts.contactGroups.map((contact) => contactGroups.contacts === undefined
|| contacts.contactGroups.map((contact) => contactGroups.contacts.length === 0 ){
return false
}
return contacts
}
The data structure looks like this:
const mockContacts = {
count: 1,
contactGroups: [
{
contactGroup: "Family",
count: 2,
contacts: [
{
member: "Uncle",
fullName: "BENJAMIN BILLIARDS",
lastName: "BILLIARDS",
firstName: "BENJAMIN",
email: "shark#billiards.com",
},
{
member: "Aunt",
fullName: "DENISE NICE",
lastName: "NICE",
firstName: "DENISE",
email: "floral#flowers.com",
}
]
},
{
contactGroup: "Friends",
count: 2,
contacts: [
{
member: "School Friend",
fullName: "DERRICK SMITH",
lastName: "SMITH",
firstName: "DERRICK",
email: "smith978#gmail.com",
},
{
member: "Work Friend",
fullName: "TARA SKY",
lastName: "SKY",
firstName: "TARA",
email: "uptown94#gmail.com",
}
]
}
If you want to return boolean if there are any contacts then you can do the following:
const hasContacts = ({ contactGroups = [] } = []) =>
contactGroups.some(
({ contacts = [] } = {}) => contacts.length
);
console.log('pass undefined', hasContacts());
console.log('pass empty object', hasContacts({}));
console.log(
'pass empty contact group',
hasContacts({ contactGroups: [] })
);
console.log(
'pass empty contacts',
hasContacts({ contactGroups: [{ contacts: [] }] })
);
console.log(
'pass contacts',
hasContacts({ contactGroups: [{ contacts: [1] }] })
);
console.log(
'pass some contacts',
hasContacts({
contactGroups: [{ contacts: [] }, { contacts: [1] }],
})
);
const mockContacts = {
count: 1,
contactGroups: [
{
contactGroup: 'Family',
count: 2,
contacts: [
{
member: 'Uncle',
fullName: 'BENJAMIN BILLIARDS',
lastName: 'BILLIARDS',
firstName: 'BENJAMIN',
email: 'shark#billiards.com',
},
{
member: 'Aunt',
fullName: 'DENISE NICE',
lastName: 'NICE',
firstName: 'DENISE',
email: 'floral#flowers.com',
},
],
},
{
contactGroup: 'Friends',
count: 2,
contacts: [
{
member: 'School Friend',
fullName: 'DERRICK SMITH',
lastName: 'SMITH',
firstName: 'DERRICK',
email: 'smith978#gmail.com',
},
{
member: 'Work Friend',
fullName: 'TARA SKY',
lastName: 'SKY',
firstName: 'TARA',
email: 'uptown94#gmail.com',
},
],
},
],
};
console.log(
'mock contacts:',
hasContacts(mockContacts)
);
Assuming the nested contactGroup contacts cannot also have more nesting then this solution should work for you. I was unclear on how you wanted to handle each nested group so I returned an array that will tell you if each nested group does or does not have contacts.
const mockContacts = {
count: 1,
contactGroups: [
{
contactGroup: "Family",
count: 2,
contacts: [
{
member: "Uncle",
fullName: "BENJAMIN BILLIARDS",
lastName: "BILLIARDS",
firstName: "BENJAMIN",
email: "shark#billiards.com",
},
{
member: "Aunt",
fullName: "DENISE NICE",
lastName: "NICE",
firstName: "DENISE",
email: "floral#flowers.com",
}
]
},
{
contactGroup: "Friends",
count: 2,
contacts: [
{
member: "School Friend",
fullName: "DERRICK SMITH",
lastName: "SMITH",
firstName: "DERRICK",
email: "smith978#gmail.com",
},
{
member: "Work Friend",
fullName: "TARA SKY",
lastName: "SKY",
firstName: "TARA",
email: "uptown94#gmail.com",
}
]
}
]
}
const hasContacts = (contacts) => {
// if contacts is not undefined, then check contactGroup
if (contacts && Array.isArray(contacts.contactGroups)) {
// we can have more than one contact group so need to check each
return contacts.contactGroups.map(row=>Array.isArray(row.contacts) && row.contacts.length > 0)
}
}
console.log(hasContacts(mockContacts))
I receive an array of objects from the server. But my app breaks because some objects do not have a structure just a null value and my logic depends on checking against certain object keys to do one thing or another. Here is an example of an array that i receive:
[{
clienTnames: {
firstName: 'Jack',
lastName: 'Jackson'
}
}, {
clienTnames: {
firstName: 'John',
lastName: 'Johnson'
}
}, {
clienTnames: null
}]
I would like to check if any objects arrive as null and if they do switch them to empty object with all the proper keys just with no value. So if I receive clienTnames: null; I would like to automatically change it to clienTnames : {firstName: ' ', lastName: ' '}
Just use a map function:
names = names.map(name => {
return name.clienTnames
? name.clienTnames
: { clienTnames: { firstName: '', lastName: '' } }
});
You can create a defaultObj with all the default properties. Then loop through the array and update items which have clienTnames property set to null
let array = [{clienTnames:{firstName:'Jack',lastName:'Jackson'}},{clienTnames:{firstName:'John',lastName:'Johnson'}},{clienTnames:null}]
const defaultObj = {
firstName: '',
lastName: ''
}
array.forEach(a => {
if(!a.clienTnames)
a.clienTnames = { ...defaultObj }
})
console.log(array)
You can do something like this:
const data = [{ clienTnames: { firstName: 'Jack', lastName: 'Jackson' } }, { clienTnames: { firstName: 'John', lastName: 'Johnson' } }, { clienTnames: null }];
let output = [];
output = data.map(element => {
if (element.clienTnames) {
return element;
} else {
return { clienTnames: { firstName: '', lastName: '' } };
}
});
console.log(output);
let array = [{
clienTnames: {
firstName: 'Jack',
lastName: 'Jackson'
}
}, {
clienTnames: {
firstName: 'John',
lastName: 'Johnson'
}
}, {
clienTnames: null
}];
let targetArray;
targetArray = array.map((item) => {
if(!item.clienTnames) {
return { clienTnames: { firstName: '', lastName: '' } }
}
return item;
})
I have 2 arrays
First array has firstname and lastname
Second array only has firstname
I will index one firstname and check the arrays
function whereIsAlice(persons) {
var index = 1;
for (var i = 0; i < friends1.length; i++) {
if (friends1[i].firstName === "Alice") {
index = i;
break;
}
if (friends2[i].firstName === "Alice") {
index = i;
}
}
return index
}
var friends1 = [{
firstName: 'John',
lastName: 'Gaudet'
},
{
firstName: 'Lisa',
lastName: 'Mcclanahan'
},
{
firstName: 'Alice',
lastName: 'Vore'
}, // Alice is here, at index 2
{
firstName: 'Marine',
lastName: 'Salsbury'
},
];
var friends2 = [{
firstName: 'Tim'
},
{
firstName: 'Arthur'
},
{
firstName: 'Juan'
},
];
console.log(whereIsAlice(friends1)); //Should be 2
console.log(whereIsAlice(friends2)); // Should be -1
The output are 2 on both. How can i fix it ?
The problem its easy. You are comparing in whereIsAlice method always the first array and the second array, then the method always find the value and break de for loop.
function whereIsAlice(names) {
for (var i = 0; i < names.length; i++) {
if (names[i].firstName == "Alice") {
return i;
}
}
// When not found in above loop then return -1, not found!
return -1;
}
var friends1 = [
{ firstName: 'John', lastName: 'Gaudet' },
{ firstName: 'Lisa', lastName: 'Mcclanahan' },
{ firstName: 'Alice', lastName: 'Vore' }, // Alice is here, at index 2
{ firstName: 'Marine', lastName: 'Salsbury' }
];
var friends2 = [
{ firstName: 'Tim' },
{ firstName: 'Arthur' },
{ firstName: 'Juan' }
];
console.log(whereIsAlice(friends1)); //Should be 2
console.log(whereIsAlice(friends2)); // Should be -1
Some of You mutating new array (array.map) from initial array and doing indexOf.
Others are looping with for and then checking the variable index.
Then why JS community is working to extend language constructions, methods and etc?
I recommend You to dive in MDN better and read about findIndex ?
function whereIsAlice(persons) {
return persons.findIndex(function(person) {
return person.firstName === 'Alice';
});
}
var friends1 = [
{
firstName: 'John',
lastName: 'Gaudet'
},
{
firstName: 'Lisa',
lastName: 'Mcclanahan'
},
{
firstName: 'Alice',
lastName: 'Vore'
}, // Alice is here, at index 2
{
firstName: 'Marine',
lastName: 'Salsbury'
},
];
var friends2 = [
{
firstName: 'Tim'
},
{
firstName: 'Arthur'
},
{
firstName: 'Juan'
},
];
console.log(whereIsAlice(friends1));
console.log(whereIsAlice(friends2));
With ES6 it's so shorter that I don't see reason to create method:
console.log(friends1.findIndex(friend => friend.firstName === 'Alice'));
console.log(friends2.findIndex(friend => friend.firstName === 'Alice'));
You can do it like this if you want to write your own loop.
var friends1 = [
{ firstName: 'John', lastName: 'Gaudet' },
{ firstName: 'Lisa', lastName: 'Mcclanahan' },
{ firstName: 'Alice', lastName: 'Vore' },
{ firstName: 'Marine', lastName: 'Salsbury' },
];
var friends2 = [
{ firstName: 'Tim' },
{ firstName: 'Arthur' },
{ firstName: 'Juan' },
];
const whereIsAlice = arr => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].firstName === 'Alice') {
return i;
}
}
return -1;
}
console.log(whereIsAlice(friends1)); //Should be 2
console.log(whereIsAlice(friends2)); // Should be -1
to simplify your Function you can use the next code
function whereIsAlice(persons) {
return persons.map(function(e) { return e.firstName; }).indexOf('Alice');
}
var friends1 = [{
firstName: 'John',
lastName: 'Gaudet'
},
{
firstName: 'Lisa',
lastName: 'Mcclanahan'
},
{
firstName: 'Alice',
lastName: 'Vore'
}, // Alice is here, at index 2
{
firstName: 'Marine',
lastName: 'Salsbury'
},
];
var friends2 = [{
firstName: 'Tim'
},
{
firstName: 'Arthur'
},
{
firstName: 'Juan'
},
];
console.log(whereIsAlice(friends1)); //Should be 2
console.log(whereIsAlice(friends2)); // Should be -1
Rewrite Your function as below, This will work properly in your case :
function whereIsAlice(persons) {
var index= -1;
for(var i=0;i<persons.length;i++)
if(persons[i].firstName==="Alice"){index=i;break;}
return index;
}
I have an array of objects, I'm trying to loop through them via map function and create an output as follows:
Desired output
dataSet = [
[John, Doe, Sales],
[Jane, Doe, HR],
[Jack, Doe, Manager]
]
My array of objects:
[[object],[object],[object]]
Here is what I have tried so far:
users.map((item) => {
dataSet.push(item.profile.firstName, item.profile.role)
})
However my output:
["John","Jane","Jack"]
How can I push each loop into new array?
Thanks
Actually, you are pretty close. Just make what you want to push an array. Try the following codes:
users.forEach((item) => {
dataSet.push([item.profile.firstName, item.profile.lastName, item.profile.role]);
});
Assuming your original data looks like:
data: [
...
{
profile: {
firstname: "John",
lastname: "Doe",
role: "Sales"
}
},
...
];
You could do this:
var dataSet = data.map((person) => {
let profile = person.profile;
return [
profile.firstname,
profile.lastname,
profile.role
];
});
Hope this helps!
When you are mapping the array of objects you should just return an array with the values you want.
const john = { firstName: 'John', lastName: 'Doe', role: 'Sales' }
const jane = { firstName: 'Jane', lastName: 'Doe', role: 'HR' }
const jack = { firstName: 'Jack', lastName: 'Doe', role: 'Manager' }
const users = [ john, jane, jack ]
const dataSet = users.map(user => ([ user.firstName, user.lastName, user.role ]))
console.log(dataSet)
You can do this in a more generic way by allowing for any number of properties on the object using map, e.g.
dataset = [
{firstName: 'John', lastName: 'Doe', role: 'Sales'},
{firstName: 'Jane', lastName: 'Doe', role: 'HR'},
{firstName: 'Jack', lastName: 'Doe', role: 'Manager'}
];
var result = dataset.map(obj => Object.keys(obj).map(key => obj[key]));
console.log(result)