I have created a dynamic array of objects which is created through inquirer.
But I cannot figure out how to access a specific object in the array
EDIT: this is how the console has logged my array
So for example, how can I access the 2nd Engineer (Mark)?
Keep in mind the array will change depending on the user input
team = [
Manager {
name: 'Nicole',
id: '1',
email: 'nicole#gmail.com',
officeNumber: '5'
},
Engineer {
name: 'Zoe',
id: '2',
email: 'zoe#gmail.com',
github: 'zozo'
},
Engineer {
name: 'Mark',
id: '3',
email: 'mark#gmail.com',
github: 'emman'
},
Engineer {
name: 'Joe',
id: '4',
email: 'joe#gmail.com',
github: 'joey'
}
Intern {
name: 'Seb',
id: '5',
email: 'seb#gmail.com',
school: 'UWA'
}
]
Use find method. If there is no such Mark then find return null.
If you want find Engineer Mark
const result = data.find(x => {
return x instanceof Engineer && x.name === 'Mark'
})
[Update]
If you want find the second Engineer
const result = data.filter(x => {
return x instanceof Engineer
})[1]
As Sepehr jozef mentioned the strucure is not that handy. If we take his structure you can find it via the .find Method.
var team = [
{
name: 'Nicole',
id: '1',
email: 'nicole#gmail.com',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: 'zoe#gmail.com',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: 'mark#gmail.com',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: 'joe#gmail.com',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: 'seb#gmail.com',
school: 'UWA'
}
]
const mark = team.find(function(teamMember){
return teamMember.name === "Mark";
})
The variable "mark" contains now the object of the engineer "Mark".
first of all, your structure is wrong.
it should be:
var team = [
{
name: 'Nicole',
id: '1',
email: 'nicole#gmail.com',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: 'zoe#gmail.com',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: 'mark#gmail.com',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: 'joe#gmail.com',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: 'seb#gmail.com',
school: 'UWA'
}
]
and to get mark(2) you should use:
team[3].name
Related
Consider the following two arrays:
[
{
id: jhz,
name: 'John',
eyes: 'Green',
description: 'Cool guy',
},
{
id: mbe,
name: 'Mary',
brand: 'M&B',
text: 'Something',
}
]
[
{
id: jhz,
name: 'John',
eyes: '',
},
{
id: mbe,
name: 'Mary',
},
{
id: 'beh',
name: 'Bernard',
}
]
First array may have any kind of key value pairs, but it will always have the key id and name. I want to merge the two arrays by taking id and name into account and preserving them, while merging everything else and replacing them with data from the first array if any keys duplicate.
Also tricky part - the merged array needs to follow the order of the second array.
So in this example the result I'm looking for is:
[
{
id: jhz,
name: 'John',
eyes: 'Green',
description: 'Cool guy',
},
{
id: mbe,
name: 'Mary',
brand: 'M&B',
text: 'Something',
},
{
id: 'beh',
name: 'Bernard',
}
]
you can do something like this using Array.map
const data1 = [{
id: 'jhz',
name: 'John',
eyes: 'Green',
description: 'Cool guy',
},
{
id: 'mbe',
name: 'Mary',
brand: 'M&B',
text: 'Something',
}
]
const data2 = [{
id: 'jhz',
name: 'John',
eyes: '',
},
{
id: 'mbe',
name: 'Mary',
},
{
id: 'beh',
name: 'Bernard',
}
]
const result = data2.map(d => ({...d, ...(data1.find(d1 => d1.id === d.id && d1.name === d.name) || {})}))
console.log(result)
This question already has answers here:
How can I perform an inner join with two object arrays in JavaScript?
(7 answers)
Closed 1 year ago.
My database gives me the following data:
var responses = [
{ comment: 'Yes', uid: '5hg' },
{ comment: 'Maybe', uid: 'f1' },
{ comment: 'No', uid: 'b1k2' },
{ comment: 'Yes', uid: '6t2' },
{ comment: 'Yes', uid: 'hd1' },
];
var users = [
{ name: 'Trevor Hansen', group: 'Group 1', uid: 'f1' },
{ name: 'Britta Holt', group: 'Group 2', uid: '5hg' },
{ name: 'Jane Smith ', group: 'Group 2', uid: '6t2' },
{ name: 'Sandra Adams', group: 'Group 1', uid: 'c92c' },
{ name: 'Ali Connors', group: 'Group 1', uid: 'b2' },
{ name: 'John Smith', group: 'Group 2', uid: '9l2' },
{ name: 'Sandra Williams', group: 'Group 2', uid: 'hd1' },
{ name: 'Tucker Smith', group: 'Group 1', uid: 'b1k2' },
];
Because I store all of my user data only in users[] for different purposes I need to add some information to responses[] about the user (like their name and group). The uid is unique and can be used to match the data to a user.
Obviously there are less responses than users in responses[]. This should not affect my function and is an expected behavior.
This is the desired output:
var output = [
{ comment: 'Yes', uid: '5hg', name: 'Britta Holt', group: 'Group 2' },
{ comment: 'Maybe', uid: 'f1', name: 'Trevor Hansen', group: 'Group 1' },
{ comment: 'No', uid: 'b1k2', name: 'Tucker Smith', group: 'Group 1' },
{ comment: 'Yes', uid: '6t2', name: 'Jane Smith ', group: 'Group 2' },
{ comment: 'Yes', uid: 'hd1', name: 'Sandra Williams', group: 'Group 2' },
];
How can this be done? Any help is appreciated!
you can try for example:
const output = responses.map(response => {
const user = users.find(u => u.uid === response.uid);
return {...response, ...user}
})
or single liner:
const output = responses.map(response => ({...response, ...users.find(u => u.uid === response.uid)}));
This question already has answers here:
Filter array of objects with another array of objects
(11 answers)
Closed 2 years ago.
I need to filter dogs and also the sitters inside this Array based on another Array sittersSelected. (It's ok to use es6). The problem for me is handling the nested array.
Not sure if it's possible but...
Data
dogs = [
{
name: 'Alice',
sex: 'Female',
breed: 'German Shepherd',
sitters: [
{
id: '123',
name: 'Abby'
},
{
id: '456',
name: 'Manny'
},
{
id: '789',
name: 'Mel'
},
]
},
{
name: 'Buckley',
sex: 'Male',
breed: 'Border Collie',
sitters: [
{
id: '321',
name: 'Gustavo'
},
{
id: '654',
name: 'Tommy'
},
]
},
{
name: 'Bear',
sex: 'Male',
breed: 'Mixed',
sitters: [
{
id: '123',
name: 'Abby'
},
{
id: '135',
name: 'Owen'
},
]
},
];
sittersSelected = ["Abby","Manny"];
Expected Output
filterResult = [
{
name: 'Alice',
sex: 'Female',
breed: 'German Shepherd',
sitters: [
{
id: '123',
name: 'Abby'
},
{
id: '456',
name: 'Manny'
},
]
},
{
name: 'Bear',
sex: 'Male',
breed: 'Mixed',
sitters: [
{
id: '123',
name: 'Abby'
},
]
},
];
I've tried
filterResult = dogs.filter(dog => dog.sitters.some(sitter => sittersSelected.includes(sitter.name)));
I managed to filter the dogs but not the sitters. Also tried other examples here on StackOverflow. Is there a way to do it? maybe with .map() ?
Thank you
1-use map to return new object contain only filtered sitters
2-use filter to return only dog have sitters
let dogs = [{ name: 'Alice', sex: 'Female', breed: 'German Shepherd', sitters: [{ id: '123', name: 'Abby' }, { id: '456', name: 'Manny' }, { id: '789', name: 'Mel' },] }, { name: 'Buckley', sex: 'Male', breed: 'Border Collie', sitters: [{ id: '321', name: 'Gustavo' }, { id: '654', name: 'Tommy' },] }, { name: 'Bear', sex: 'Male', breed: 'Mixed', sitters: [{ id: '123', name: 'Abby' }, { id: '135', name: 'Owen' },] },];
let sittersSelected = ["Abby", "Manny"];
dogs.map(dog => {
return {
...dog,
sitters: dog.sitters.filter(sitter => sittersSelected.includes(sitter.name))
}
}).filter(dog => dog.sitters.length > 0);
You'll need 2 steps.
First filter each sitters sub-array to include only the ones selected.
Filter out the parent array items by whether the sitters array contains any elements:
const dogs=[{name:"Alice",sex:"Female",breed:"German Shepherd",sitters:[{id:"123",name:"Abby"},{id:"456",name:"Manny"},{id:"789",name:"Mel"}]},{name:"Buckley",sex:"Male",breed:"Border Collie",sitters:[{id:"321",name:"Gustavo"},{id:"654",name:"Tommy"}]},{name:"Bear",sex:"Male",breed:"Mixed",sitters:[{id:"123",name:"Abby"},{id:"135",name:"Owen"}]}];
const sittersSelected = ["Abby","Manny"];
for (const dog of dogs) {
dog.sitters = dog.sitters.filter(s => sittersSelected.includes(s.name));
}
const filteredDogs = dogs.filter(
dog => dog.sitters.length
);
console.log(filteredDogs);
If you don't want to mutate the input array of objects, you can map it first to clone each dog.
I have an array of objects, that looks like this:
data = [
{
title: 'John Doe',
departments: [
{ name: 'Marketing', slug: 'marketing'},
{ name: 'Sales', slug: 'sales'},
{ name: 'Administration', slug: 'administration'},
]
},
{
title: 'John Doe Junior',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Sales', slug: 'sales'},
]
},
{
title: 'Rick Stone',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Marketing', slug: 'marketin'},
]
},
]
How can I iterate over each object's departments array and create new arrays where I would have employees sorted by departments, so that the end result would like this:
operations = [
{
title: 'John Doe Junior',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Sales', slug: 'sales'},
]
},
{
title: 'Rick Stone',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Marketing', slug: 'marketin'},
]
},
]
marketing = [
{
title: 'John Doe',
departments: [
{ name: 'Marketing', slug: 'marketing'},
{ name: 'Sales', slug: 'sales'},
{ name: 'Administration', slug: 'administration'},
]
},
{
title: 'Rick Stone',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Marketing', slug: 'marketin'},
]
},
]
What would be the way to create dynamically this kind of arrays?
Update
I have tried to come up with a solution using the suggestion from the answer, where I would dynamically create an array with department objects that would have an array of employees:
const isInDepartment = departmentToCheck => employer => employer.departments.find(department => department.slug == departmentToCheck);
var departments = [];
function check(departments, name) {
return departments.some(object => name === object.department);
}
employees.forEach((employee) => {
employee.departments.forEach((department) => {
let found = check(departments, department.slug);
if (!found) {
departments.push({ department: department.slug });
}
});
});
departments.forEach((department) => {
// push an array of employees to each department
//employees.filter(isInDepartment(department));
});
But, I don't know how can I push the array of employees to the object in the array that I am looping at the end?
This is the fiddle.
How about this? I use Array.protoype.filter operation, and I use a higher-order function (in this case a function that returns a function) to create the predicate (function that returns a boolean) that will check whether an employee is in a specific department. I added some (hopefully) clarifying comments in the code.
Edit: with the new code and context you provided this JSFiddle demo shows how it would work together.
const employees = [
{
title: 'John Doe',
departments: [
{ name: 'Marketing', slug: 'marketing'},
{ name: 'Sales', slug: 'sales'},
{ name: 'Administration', slug: 'administration'}
]
},
{
title: 'John Doe Junior',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Sales', slug: 'sales'}
]
},
{
title: 'Rick Stone',
departments: [
{ name: 'Operations', slug: 'operations'},
{ name: 'Marketing', slug: 'marketin'}
]
}
];
// given a department, this returns a function that checks
// whether an employee is in the specified department
// NOTE: the "find" returns the found object (truthy)
// or undefined (falsy) if no match was found.
const isInDepartment =
departmentToCheck =>
employee => employee.departments.find(dep => dep.name == departmentToCheck);
const employeesInMarketing = employees.filter(isInDepartment('Marketing'));
const employeesInOperations = employees.filter(isInDepartment('Operations'));
console.log('Employees in marketing', employeesInMarketing);
console.log('Employees in operations', employeesInOperations);
I'm trying to filter this array to get the id and convert from a string to a number. I want to use filter and map? Wanting to know how to make it as clear as possible.
var pets = [
{ id: '1', name: 'rupert', readyForHome: 'No', age: 12, personality: ['friendly', 'lazy', 'loving']},
{ id: '2', name: 'mrs fluffy', readyForHome: 'Yes', age: 2, personality: ['affectionate', 'playful', 'shy']},
{ id: '3', name: 'tabitha', readyForHome: 'Yes', age: 4, personality: ['aggressive', 'independent']},
{ id: '4', name: 'lily', readyForHome: 'No', age: 8, personality: ['friendly', 'playful', 'mischievous']},
];
All you need is map to get down to an array of ids as numbers:
pets = pets.map(function(pet) {
return Number(pet.id);
});
var pets=[{id:"1",name:"rupert",readyForHome:"No",age:12,personality:["friendly","lazy","loving"]},{id:"2",name:"mrs fluffy",readyForHome:"Yes",age:2,personality:["affectionate","playful","shy"]},{id:"3",name:"tabitha",readyForHome:"Yes",age:4,personality:["aggressive","independent"]},{id:"4",name:"lily",readyForHome:"No",age:8,personality:["friendly","playful","mischievous"]}];
pets = pets.map(function(pet) {
return Number(pet.id);
});
console.log(pets);
var petIds = pets.map(function (pet) {
petId = parseInt(pet.id);
return petId;
});