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)
Related
So i have an array of objects which I want to filter with a search input.
const people = [
{
firstName: 'John',
lastName: 'Doe',
},
{
firstName: 'Jane',
lastName: 'Doe',
}
];
I made this function to take a list and a search value so It could return filtered list.
const filterList = (list, searchValue) => {
let filtered = list.filter(item => {
let fullName = item.firstName.toLowerCase() + item.lastName.toLowerCase()
let trimmedSearchValue = searchValue.replace(/\s+/g, '');
return fullName.includes(trimmedSearchValue.toLowerCase())
})
return filtered
}
Filtering works when I call it like this
console.log(filterList(people, 'john'))
// returns { firstName: "John", lastName: "Doe"}
console.log(filterList(people, 'jane'))
// returns { firstName: "Jane", lastName: "Doe"}
console.log(filterList(people, 'doe'))
// returns both objects [
// { firstName: "John", lastName: "Doe"},
// { firstName: "Jane", lastName: "Doe"}
// ]
But when I call it like this I get empty array as a result
console.log(filterList(people, 'doe j'))
//returns empty array [], expected to get back both objects
console.log(filterList(people, 'doe john'))
//returns empty array [], expected to get {firstName: "John", lastName: "Doe"}
I think I am not correctly comparing fullName with searchValue but I couldn't figure it out.
You can compare with the lastName+firstName as well:
const filterList = (list, searchValue) => {
return list.filter(item => {
const fullName = `${item.firstName}${item.lastName}`.toLowerCase();
const reversedFullName = `${item.lastName}${item.firstName}`.toLowerCase();
const trimmedSearchValue = searchValue.replace(/\s+/g, '').toLowerCase();
return fullName.includes(trimmedSearchValue) || reversedFullName.includes(trimmedSearchValue);
});
}
const people = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Jane', lastName: 'Doe' }
];
console.log(filterList(people, 'doe j'));
console.log(filterList(people, 'doe john'));
You can do something like this:
const people = [
{
firstName: 'John',
lastName: 'Doe',
},
{
firstName: 'Jane',
lastName: 'Doe',
}
];
const filterList = (list, searchValue) => {
let filtered = list.filter(item => {
const arr = searchValue.split(' ');
return arr.some(el => item.firstName.toLowerCase().includes(el) || item.lastName.toLowerCase().includes(el));
})
return filtered
}
console.log(filterList(people, 'doe j'))
This should do the job too:
const people = [{firstName: 'John',lastName: 'Doe'},
{firstName: 'Jane',lastName: 'Doe'}];
function find(arr,pat){
let pa=pat.trim().replace(/ +/g," ").split(" ")
.map(p=>new RegExp(p,"i"));
return arr.filter(n=>{
let name=n.firstName+" "+n.lastName;
return pa.every(p=>p.test(name))
})
}
["doe j","john","jan do"].forEach(t=> // test cases ...
console.log(find(people,t))
)
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);
I have an array who look like this:
tab [
0: {
firstName: John,
lastName: Doe,
situation: married,
familyMembers: 5,
}
1: {
firstName: Jack,
lastName: Daniel,
situation: single,
familyMembers: 6,
}
]
I need something like this:
{
[John]: {[Doe]: 5,
[Jack]: {[Daniel]: 6,
}
I tried something like this:
tab.map((item) => {
return (
{[item.firstName]: {[item.lastName]: item.familyMembers}}
)
})
But even without considering that I have an array instead of an object the result look like this:
[
0: {
[John]: {[Doe]: 5,
}
1: {
[Jack]: {[Daniel]: 6,
}
]
Any suggestion here will be appreciate I tried using reduce but as I probably don't use it well it make really bad result.
Assuming, you wnat the names as keys, yxou could build the entries and from it the object.
var tab = [{ firstName: 'John', lastName: 'Doe', situation: 'maried', familyMembers: 5 }, { firstName: 'Jack', lastName: 'Daniel', situation: 'single', familyMembers: 6 }],
result = Object.fromEntries(tab.map(({ firstName, lastName, familyMembers }) =>
[firstName, { [lastName]: familyMembers }]
));
console.log(result);
map() always returns an array of the results of the function.
You can use reduce() instead
var tab = [{
firstName: 'John',
lastName: 'Doe',
situation: 'maried',
familyMembers: 5,
},
{
firstName: 'Jack',
lastName: 'Daniel',
situation: 'single',
familyMembers: 6,
}
];
var result = tab.reduce((obj, item) => {
obj[item.firstName] = {
[item.lastName]: item.familyMembers
};
return obj;
}, {});
console.log(result);
I know how to operate on array of objects but never had the necessity to populate an array data into another. I need to populate firstname + lastname field into name field of birth array
let birth = [
{name: '' }
]
firstly my array is empty and i want to poplulate it with these datas
let names = [
{firstname: "Julien", lastname: "DEHAIS"},
{firstname: "Cyril", lastname: "GUIGUIAN"},
{firstname: "Pascal", lastname: "BOUTRIN"},
{firstname: "Franck", lastname: "BORDERIE"},
{firstname: "Arnold", lastname: "GIRARD"}
]
to get something like this
let birth = [
{name: 'Julien DEHAIS' },
{name: 'Cyril GUIGUIAN' },
{name: 'Pascal BOUTRIN' },
{name: 'Franck BORDERIE' },
{name: 'Arnold GIRARD' }
]
Kindly someone help me in this please
Simple map:
let names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
const res = names.map(({ firstname, lastname }) => ({ name: firstname + " " + lastname }));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5 syntax:
var names = [{firstname:"Julien",lastname:"DEHAIS"},{firstname:"Cyril",lastname:"GUIGUIAN"},{firstname:"Pascal",lastname:"BOUTRIN"},{firstname:"Franck",lastname:"BORDERIE"},{firstname:"Arnold",lastname:"GIRARD"}];
var res = names.map(function(e) {
return { name: e.firstname + " " + e.lastname };
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
You can use map() and return a new object with name property
let names = [ {firstname: "Julien", lastname: "DEHAIS"}, {firstname: "Cyril", lastname: "GUIGUIAN"}, {firstname: "Pascal", lastname: "BOUTRIN"}, {firstname: "Franck", lastname: "BORDERIE"}, {firstname: "Arnold", lastname: "GIRARD"} ]
const res = names.map(x => ({name: `${x.firstname} ${x.lastname}`}))
console.log(res)
I've found a lot of similar questions but they explain how to remove duplicate objects. In this case, I need to create a new array that doesn't include objects which were found in two arrays.
const firstArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'},
{firstName: 'Mike', lastName: 'Hunt'},
{firstName: 'Steve', lastName: 'Irvine'}
];
const secondArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'}
];
The expected result for the previous sample of data should be:
const result = [
{firstName: 'Mike', lastName: 'Hunt'},
{firstName: 'Steve', lastName: 'Irvine'}
];
I will first concatenate both arrays and then filter() those elements that don't appear on both arrays using some() for search on each of the arrays. Note this approach take into account the possibility that both the firstArray and the secondArray can contain non-duplicated objects.
const firstArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'},
{firstName: 'Mike', lastName: 'Hunt'},
{firstName: 'Steve', lastName: 'Irvine'}
];
const secondArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'},
{firstName: 'Joseph', lastName: 'Muguera'}
];
let res = firstArray.concat(secondArray).filter(({firstName, lastName}) =>
{
let foundOnFirst = firstArray.some(
x => x.firstName === firstName && x.lastName === lastName
);
let foundOnSecond = secondArray.some(
y => y.firstName === firstName && y.lastName === lastName
);
return !(foundOnFirst && foundOnSecond);
});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
You could filter firstArray by iterating secondArray and check the wanted properties for compairing.
const
firstArray = [{ firstName: 'John', lastName: 'Doe' }, { firstName: 'Sara', lastName: 'Connor' }, { firstName: 'Mike', lastName: 'Hunt' }, { firstName: 'Steve', lastName: 'Irvine' }],
secondArray = [{ firstName: 'John', lastName: 'Doe' }, { firstName: 'Sara', lastName: 'Connor' }],
result = firstArray.filter(o =>
secondArray.every(p =>
!['firstName', 'lastName'].some(k => o[k] === p[k])));
console.log(result);
An approach with a Set of joined properties.
const
firstArray = [{ firstName: 'John', lastName: 'Doe' }, { firstName: 'Sara', lastName: 'Connor' }, { firstName: 'Mike', lastName: 'Hunt' }, { firstName: 'Steve', lastName: 'Irvine' }],
secondArray = [{ firstName: 'John', lastName: 'Doe' }, { firstName: 'Sara', lastName: 'Connor' }],
getKey = ({ firstName, lastName }) => [firstName, lastName].join('|'),
secondSet = new Set(firstArray.map(getKey)),
result = firstArray.filter(o => !set.has(getKey(o)));
console.log(result);
You can filter one array and compare object with JSON.stringify with second array,
const firstArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'},
{firstName: 'Mike', lastName: 'Hunt'},
{firstName: 'Steve', lastName: 'Irvine'}
];
const secondArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'}
];
const res=firstArray.filter(function(obj) {
// JSON.stringify(obj)==JSON.stringify(obj)
for( var i=0, len=secondArray.length; i<len; i++ ){
if(JSON.stringify(obj)==JSON.stringify(secondArray[i]) ) {
return false;
}
}
return true;
});
console.log(res);
An alternative approach can be based on .findIndex() and JSON.stringify():
const firstArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'},
{firstName: 'Mike', lastName: 'Hunt'},
{firstName: 'Steve', lastName: 'Irvine'}
];
const secondArray = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Sara', lastName: 'Connor'}
];
const result = firstArray.filter(ele =>
secondArray.findIndex(ele1 =>
JSON.stringify(ele1) == JSON.stringify(ele)) == -1
);
console.log(result);