join object with the same name into one item - javascript

I want to join the objects with the same name into one item array and i don't know how to do it.
I have an array like this :
[
{ name: 'core/core.js',
item: [ [Object] ] },
{ name: 'users/admin.js',
item: [ [Object] ] },
{ name: 'users/admin.js',
item: [ [Object] ] }
]
and i want to have something similar to this :
[
{ name: 'core/core.js',
item: [ [Object] ] },
{ name: 'users/admin.js',
item: [
[ [Object] ],
[ [Object] ]
]
},
]
Here is my code:
const pathFile = [
{ name: 'core/core.js', item: [{ name: 'core' }] },
{ name: 'users/admin.js', item: [{ name: 'admin1' }] },
{ name: 'users/admin.js', item: [{ name: 'admin2' }] },
];
const obj = pathFile.reduce((a, name) => {
if (!a[name]) {
a[name] = { name, files: [] };
}
a[name].files.push({ name });
return a;
}, {});
const arr = Object.values(obj);
console.log(JSON.stringify(arr));

Your problem is that you are using the wrong value for keys inside your reduce() loop. In your code name refers to the whole object inside the reduce so you would need to use name.name for the key because each item, which you are calling name inside the reduce loop has a name property. It might be better to use a different parameter name such as curr so it's clearer.
const pathFile = [{ name: 'core/core.js', item: [{ name: 'core' }] },{ name: 'users/admin.js', item: [{ name: 'admin1' }] },{ name: 'users/admin.js', item: [{ name: 'admin2' }] },];
const obj = pathFile.reduce((a, curr) => {
if (!a[curr.name]) a[curr.name] = curr
else a[curr.name].item.push(...curr.item);
return a;
}, {});
const arr = Object.values(obj);
console.log(arr)

Related

How to check array of objects based on ID and add new property in JavaScript

I have two array of objects arr1 and arr2
if arr1 and arr2 id matches, then push arr1 property name to arr2 in javascript
var arr1 = [
{id: 1, name : "Helena"},
{id: 2, name : "John"}
]
var arr2 = [{
country: "MY",
details: [{
mode: "parttime",
members:[{id:1}, {id: 2}]
}]
}]
Expected Output:
[{
country: "MY",
details:[{
mode: "parttime",
members: [
{id:1, name: "Helena"},
{id: 2, name: "john"}
]
}]
}]
Please try:
var arr1 = [
{
id: 1,
name: "Helena",
},
{
id: 2,
name: "John",
},
];
var arr2 = [
{
country: "MY",
details: [
{
mode: "parttime",
members: [
{
id: 1,
},
{
id: 2,
},
],
},
],
},
];
function getCountriesWithMemberNames(membersArr, countriesArr) {
// mapping each country obj in the array to a modified country
return countriesArr.map((country) => {
return {
...country, // take all existing country info
// modify country.details, mapping it to a new object
details: country.details.map((detail) => {
return {
...detail, // take all details
// modying members
members: detail.members.map((member) => {
const memberObj = { ...member };
// check if name exists for this member
const name = membersArr.find((i) => i.id === member.id).name;
if (name) {
memberObj.name = name;
}
return memberObj;
}),
};
}),
};
});
}
console.log(getCountriesWithMemberNames(arr1, arr2));

Underscore.js: filter objects with nested array of objs

I am trying to filter top-level objects based on nested data (filtering is also needed for nested objects).
Filter params: All records with categoryValue A.
const table = [
{
name: 'Bob',
detail: [
{ category: 'Employeer', categoryValue: 'A' },
{ category: 'Employeer', categoryValue: 'B' },
],
},
{
name: 'Alice',
detail: [
{ category: 'Employeer', categoryValue: 'C' },
{ category: 'Employeer', categoryValue: 'D' },
],
},
];
I am expecting the following result
const fileredTable = [
{
//this
name: 'Bob',
detail: [
//and only this
{ category: 'Employeer', categoryValue: 'A' }
],
}
];
Ok, after several tries i found this solution:
const filteredTable = table.flatMap((item) => {
const filteredDetail = item.detail.filter((e) => e.categoryValue === 'A')
return filteredDetail.length !== 0 ? {...item, detail: filteredDetail} : []
})

JavaScript clean array object

Hello I have a array of objects that contain array of objects. I would like to know how I can clean properties empty if my user search leather for example.
My result:
let cars = [{
name: 'Volvo',
equipments: [
{ name: 'saddleries', options: [{title: 'leather'}] },
{ name: 'wheels', options: [title: 'sliver'}] },
{ name: 'motor', options: [] }]
}];
I would like this result :
let cars = [{
name: 'Volvo',
equipments: [
{ name: 'saddleries', options: [{title: 'leather'}] },
{ name: 'wheels', options: [title: 'sliver'}] },
}];
How I can remove my data please ? thanks
Check this code
let cars = [{
name: 'Volvo',
equipments: [
{ name: 'saddleries', options: [{title: 'leather'}] },
{ name: 'wheels', options: [{title: 'sliver'}] },
{ name: 'motor', options: [] }]
}];
cars.forEach((c) => {
c.equipments = c.equipments.filter(e => e.options.length !== 0);
})
console.log(cars)
Try this:
var cars = {
name: 'Volvo',
equipments: [{
name: 'saddleries',
options: [{
title: 'leather'
}]
},
{
name: 'wheels',
options: [{
title: 'sliver'
}]
},
{
name: 'motor',
options: []
},
{
name: 'handles',
options: []
}
]
};
carsCopy = Object.assign([], cars.equipments)
var count = 0
cars.equipments.forEach(function(data, index) {
if (data.options.length === 0) {
carsCopy.splice(index - count, 1);
count++;
}
})
console.log(carsCopy)

Javascript : Merge objects in array with the same key not working

I am trying to get the same group names to merge together. I have looked around to get an idea of how to do this so I have done some research and I wrote the below code.
This is my implementation that isn't working:
const input = [
{ people: [{ names: "John" }, { names: "Sam" }], group: "one", },
{ people: [{ names: "George" }], group: "one", },
{ people: [{ names: "Bella" }], group: "two",},
];
var output = [];
input.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.group == item.group;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].people = output[existingIndex].people.concat(item.people);
}
});
console.log(output)
Desired Output:
const output = [
{
people: [{ names: "John" }, { names: "Sam" }, { names: "George" }],
group: "one",
},
{
people: [{ names: "Bella" }],
group: "two",
},
];
Using Array.reduce, you can group by the current array using group key.
And from that grouped object, you can get the result you want.
const input = [
{
people: [{ names: "John" }, { names: "Sam" }],
group: "one",
},
{
people: [{ names: "George" }],
group: "one",
},
{
people: [{ names: "Bella" }],
group: "two",
},
];
const groupByKey = input.reduce((acc, cur) => {
acc[cur.group] ? acc[cur.group].people.push(...cur.people) : acc[cur.group] = cur;
return acc;
}, {});
const output = Object.values(groupByKey);
console.log(output);

Search for an object in a recursive object structure (representing a file system)

I'd like to pass as an input the name of a folder that I want to search for, and get as an output the object that it belongs to.
My array is like this:
const array = {
item: [{
name: "parentFolder1",
item: [{
name: "subFolder1",
item: []
},
{
name: "subFolder2",
item: []
}
]
},
{
name: "parentFolder2",
item: [{
name: "sub1",
item: []
},
{
name: "sub2",
item: []
}
]
}
]
};
const sub = Object.values(array).map(x =>
x.find(y => y.item.find(obj => obj.name = "sub2")))
console.dir(sub)
The output I want:
{
name: "sub2",
item: []
}
The output I get:
[ { name: 'parentFolder1', item: [ [Object], [Object] ] } ]
const array = {
item: [{
name: "parentFolder1",
item: [{
name: "subFolder1",
item: []
},
{
name: "subFolder2",
item: []
}
]
},
{
name: "parentFolder2",
item: [{
name: "sub1",
item: []
},
{
name: "sub2",
item: []
}
]
}
]
};
const val = array.item.map(folder => folder.item.find(obj => obj.name === "sub2")).find(val => val)
console.log(val)
If you need it to be recursive
function find(name, obj) {
if(obj.name === name) return obj;
return obj.item.reduce((result, item) => result || find(name, item), false)
}
const array = {
item: [{
name: "parentFolder1",
item: [{
name: "subFolder1",
item: []
},
{
name: "subFolder2",
item: [{
name: "subsub",
item: [{
name: "searchme",
item: []
}]
}]
}
]
},
{
name: "parentFolder2",
item: [{
name: "sub1",
item: []
},
{
name: "sub2",
item: []
}
]
}
]
};
console.log(find("searchme", array))

Categories

Resources