Merge array of objects preserving some key-values php - javascript

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)

Related

Filtering array based on selected object in JS

Trying to get the filtered array based on the selected object. How can I loop through damaged array which is inside the object and get the resultant array? I tried to add another condition using .map but it prints the rest of the items as well.
Below is the snippet
const inventory = [{
name: 'Jeep',
id: '100',
damaged: [{
name: 'Wrangler',
id: '200'
},
{
name: 'Sahara',
id: '201'
}
]
}, {
name: 'Audi',
id: '101',
damaged: [{
name: 'Q3',
id: '300'
}]
}]
const purchasedCars = [{
car: 'Jeep',
id: '100'
}, {
car: 'Jeep - Wrangler',
id: '200',
},
{
car: 'Jeep - Sahara',
id: '201'
},
{
car: 'Audi - Q3',
id: '300'
}
]
const selectedCar = purchasedCars[0];
const filterCars = () => {
const result = purchasedCars.filter((inv) => inv.id === selectedCar.id)
console.log('result -->', result);
}
filterCars();
Expected output is
[{
car: 'Jeep',
id: '100'
},
{
car: 'Jeep - Wrangler',
id: '200',
},
{
car: 'Jeep - Sahara',
id: '201'
}]
Could anyone please help?
Trying to read your mind here. Is this what you want?
const inventory = [{
name: 'Jeep',
id: '100',
damaged: [{
name: 'Wrangler',
id: '200'
},
{
name: 'Sahara',
id: '201'
}
]
}, {
name: 'Audi',
id: '101',
damaged: [{
name: 'Q3',
id: '300'
}]
}]
const purchasedCars = [{
car: 'Jeep',
id: '100'
}, {
car: 'Jeep - Wrangler',
id: '200',
},
{
car: 'Jeep - Sahara',
id: '201'
},
{
car: 'Audi - Q3',
id: '300'
}
]
const selectedCar = purchasedCars[0];
const filterCars = () => {
let result;
const parentItem = inventory.filter((inv) => inv.id === selectedCar.id)[0];
if ("damaged" in parentItem) {
result = [selectedCar, ...(parentItem.damaged)];
}
console.log('result -->', result);
}
filterCars();
Note that if you can have more nested car types in the damaged property you would you to call filterCars recursively and pass in the car object. If you also want to filters items that may also be present in the damaged property, then you would first need to use the flatMap method (before the filter).

How can I access a specific object in my array using JavaScript?

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

How to filter an Array of Objects inside another Array of Objects in JavaScript (es6)? [duplicate]

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.

How to iterate through an array of object properties, in an array of objects

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);

Get elements from two arrays and update/replace them in another

I need to get the ID’s from arr1 that match names in arr2 and replace/add these name ID pairs into arr3.
arr1: {
[
id: [1234, 12345],
name: ‘one’,
},
{
id: [1270, 67812],
name: ‘two’,
},
{
id: [4970, 5170],
name: ’three’,
},
{
id: [02413, 02613],
name: ‘four’,
},
{
id: [8970],
name: ‘five’,
},
{
id: [7170, 6570, 6370],
name: ‘six’,
},
{
id: [8170, 22012, 4578, 33613],
name: ‘seven’,
},
{
id: [21812, 6170, 20412, 42812, 22012, 8170],
name: ‘eight’,
}]
arr2: [{
name: ‘one’,
}, {
name: ‘two’,
}, ]`
This would be result that needs to get pushed into a third array replacing the name elements with both names and ids.
arr3: [{
id: [1234, 12345],
name: ‘one’,
}, {
id: [1270, 67812],
name: ‘two’,
}

Categories