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);
Related
I have an array of object as below:
let arr = [{
id: 1,
name: 'John',
lastName: 'Smith'
},
{
id: 2,
name: 'Jill',
lastName: 'Smith'
}
];
I want to update an object with id = 1 with some properties from another object.
const obj = {
id: 1,
name: 'JOHn1'
}
The expected out is:
[{
id: 1,
name: 'JOHn1',
lastName: 'Smith'
},
{
id: 2,
name: 'Jill',
lastName: 'Smith'
}
]
I tried using Object.assign(), but it does not work. Could anyone please let me know.
arr = Object.assign(arr, obj);
thanks
thanks
You need to find the entry which you want to use as the assign target first: in this case, you need to query for the entry where id is 1. This can be done by using Array.prototype.find to locate the target, and then do Object.assign() on the target itself.
Since the found object is pass-by-reference, updating the object directly will update its entry in your array of objects directly.
See proof-of-concept below:
const arr = [{
id: 1,
name: 'John',
lastName: 'Smith'
},
{
id: 2,
name: 'Jill',
lastName: 'Smith'
}
];
const obj = {
id: 1,
name: 'JOHn1'
};
const foundObj = arr.find(({ id }) => id === obj.id);
if (foundObj) {
Object.assign(foundObj, obj);
}
console.log(arr);
Create a function, which removes all fields except 'firstName' and 'lastName' from the objects.
This is the code I've written. Any recommendations?
let people = [
{
firstName: 'John',
lastName: 'Clark',
gender: 'male'
},
{
firstName: 'Kaily',
lastName: 'Berserk',
gender: 'female'
},
{
firstName: 'Steven',
lastName: 'Bergeron',
gender: 'male'
}
];
function removeAllExceptNames(arr) {
let first = 'firstName';
let last = 'lastName';
return arr.forEach(p => {
if (p !== first || p !== last) {
delete arr[p];
}
})
}
console.log(removeAllExceptNames(people));
console.log(people);
I have 2 arguments in the function, the arr and the names
arr is the given array, names is the list of fields you want to keep in the array
I used forEach twice.. the first time was for the arr, the second time was for the Object's keys for each index in arr and that is where the exception names can be related to fields in the array of objects
let people = [
{
firstName: 'John',
lastName: 'Clark',
gender: 'male'
},
{
firstName: 'Kaily',
lastName: 'Berserk',
gender: 'female'
},
{
firstName: 'Steven',
lastName: 'Bergeron',
gender: 'male'
}
];
function removeAllExceptNames(arr,names) { //arr is the same, names is a list of names you want to keep
arr.forEach(a=>{
Object.keys(a).forEach(b=>{
if(!names.includes(b)){delete(a[b])}
})
})
}
removeAllExceptNames(people,["firstName","lastName"]);
console.log(people);
You can make use of map along with Object.fromEntries to get the expected output:
const people = [ { firstName: 'John', lastName: 'Clark', gender: 'male' }, { firstName: 'Kaily', lastName: 'Berserk', gender: 'female' }, { firstName: 'Steven', lastName: 'Bergeron', gender: 'male' }];
const keepProp=(arr, keepProp)=>arr.map(o=>Object.fromEntries(keepProp.map(n=>[n,o[n]])));
console.log(keepProp(people, ['firstName','lastName']))
I think we need to understand what the keyword delete does. The Mozilla Foundation says
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
In your scenario, you successfully removed the reference but the list is not re-ordered. It only gets replaced with an undefined. We can achieve the same thing by using the splice array function. This will remove the element and re-order.
function removeAllExceptNames(arr,firstName,lastName) {
let instancesOfNamesInArray = arr.filter(e => e.firstName == firstName || e.lastName == lastName);
// We loop through this instances and remove them from the array
instancesOfNamesInArray.foreach((item) => {
arr.splice(arr.indexOf(item),1); // Will remove the item from the array
});
}
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 of objects. I'd like to run a global search accross all values within each object and return that object.
Data
const data = [
{
firstName: 'Brady',
lastName: 'Smith'
},
{
firstName: 'Jason',
lastName: 'Brady'
},
{
firstName: 'Michael',
lastName: 'Bolten'
}
];
How do I search for Brady across all values to return both Brady Smith and Jason Brady objects? If there is an es6 way that would be great.
Current attempt
const filteredData = data
.map(item => {
if (Object.values(item) === 'Brady') {
return item;
}
})
.filter(function(element) {
return element != null;
});
No need to map the array.
You can use filter and includes to check if a string is on the array.
const data = [{
firstName: 'Brady',
lastName: 'Smith'
},
{
firstName: 'Jason',
lastName: 'Brady'
},
{
firstName: 'Michael',
lastName: 'Bolten'
}
];
const filteredData = data.filter(o => Object.values(o).includes('Brady'));
console.log(filteredData);
You can simply use filter and find
const data = [{firstName: 'Brady',lastName: 'Smith'},{firstName: 'Jason',lastName: 'Brady'},{firstName: 'Michael',lastName: 'Bolten'}];
const filteredData = data.filter(data=>
Object.values(data).some(val=> val === 'Brady')
)
console.log(filteredData)
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)