How to get all the 'items' data from this list? - javascript

I have a list of data like below:
The data consist of 6 categories (bags, shoes, girls, bags, and boys) and all of them store the same data (id, items(array: desc, id, imageUrl, name, price), routeName, title).
Now, I want to loop through all categories and just retrieve their name from the 'items', how can I do this?
I have tried the code below and I just can retrieve the name from one of the categories. Are there any ways to get all of the names from all collections? Thanks for helping me.
const { bags, shoes, girls, bags, boys } = collections;
const {items} = bags;
console.log(items.map(item => item.name));

I used this sample data object which mapping with your example. using below array functions can get the result more efficiently.
const data = {
bags: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Rabbit Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Cat Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "Parrot Crossbody", price:"$10" },
],
routeName:"bags",
title:"Bags"
},
boys: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Lion Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Dog Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "Crow Crossbody", price:"$10" },
],
routeName:"boys",
title:"Boys"
},
girls: {
id: 1,
items: [
{ desc: "abc", id: 1, imageUrl: "url", name: "Pig Crossbody", price:"$10" },
{ desc: "qwe", id: 2, imageUrl: "url", name: "Hen Crossbody", price:"$10" },
{ desc: "pqr", id: 3, imageUrl: "url", name: "fish Crossbody", price:"$10" },
],
routeName:"girls",
title:"Girls"
}};
const categories = Object.keys(data); // extract categories
const filteredNames = categories.map(category => {
const items = data[category].items; // extract items of each category
return items.map(item => item.name); // extract names of items into new[]
});
console.log('names', filteredNames.flat());
// ["Rabbit Crossbody", "Cat Crossbody", "Parrot Crossbody", "Lion Crossbody", "Dog Crossbody", "Crow Crossbody", "Pig Crossbody", "Hen Crossbody", "fish Crossbody"]

Try 2 loops:
const allNames = [];
for (const collection of Object.values(collections)) {
for(const item of collection.items) {
allNames.push(item.name);
}
}
console.log(allNames);
It's possible to do this with array functions too, but a loop is often the most obvious.

Related

How to the get the sum of all the field with the same name in a nested array?

I'm trying to find the sum of all the field values of the nested array, I suck at explaining stuffs like this, I hope the code below will give you some insight of what I want to do.
The array looks like this
data = [
{
id: 8434,
name: listName,
data: [
{name: "a name",
quantity: 20,
}
{name: "another name",
quantity: 40,
}
{name: "another new name",
quantity: 40,
}
]
},
{
id: 54343,
name: "new list name",
data: [
{name: "a name",
quantity: 12,
}
{name: "another name",
quantity: 10,
}
{name: "another new name",
quantity: 16,
}
]
}
]
This is how I want the data to be after carrying out the sum
transformed = [
{name: "a name", quantity: 32},
{name: "another name", quantity: 50},
{name: "another new name", quantity: 56}
]
You can use Array.flatMap() followed by Array.reduce() to get the desired result.
We start by calling .flatMap() to get all the data values, then calling .reduce() on these to sum each value by name.
This will create an object, with a property for each name, we then call Object.values() to return to an array.
const data = [ { id: 8434, name: 'listName', data: [ { name: "a name", quantity: 20, }, { name: "another name", quantity: 40, }, { name: "another new name", quantity: 40, } ] }, { id: 54343, name: "new list name", data: [ { name: "a name", quantity: 12, }, { name: "another name", quantity: 10, }, { name: "another new name", quantity: 16, } ] } ];
const transformed = Object.values(data.flatMap(({ data }) => data).reduce((acc, { name , quantity }) => {
acc[name] = acc[name] || { name, quantity: 0 };
acc[name].quantity += quantity;
return acc;
}, {}))
console.log('Transformed:', transformed)
.as-console-wrapper { max-height: 100% !important; }
just loop them through and create a new object..
const data = [
{
id: 8434,
name: 'listName',
data: [
{
name: "a name",
quantity: 20,
},
{
name: "another name",
quantity: 40,
},
{
name: "another new name",
quantity: 40,
}
]
},
{
id: 54343,
name: "new list name",
data: [
{
name: "a name",
quantity: 12,
},
{
name: "another name",
quantity: 10,
},
{
name: "another new name",
quantity: 16,
}
]
}
]
// Logic:
const transformed = []
data.forEach(d => {
d.data.forEach(item => {
const exist = transformed.find(t => t.name == item.name)
if(exist)
exist.quantity += item.quantity
else
transformed.push(item)
})
})
console.log(transformed)
Output:
[
{ name: 'a name', quantity: 32 },
{ name: 'another name', quantity: 50 },
{ name: 'another new name', quantity: 56 }
]
const transform = (data) => {
const quantitySum = new Map()
data.forEach(list => {
list.data.forEach(({ name, quantity }) => {
if (quantitySum.has(name)) {
quantitySum.set(name, quantitySum.get(name) + quantity)
} else {
quantitySum.set(name, quantity)
}
})
})
return Array.from(quantitySum.entries())
.map(([name, sum]) => ({
name,
quantity: sum
}))
}

Filter object array based on category and return list of matches React TS

I am having trouble filtering an object array, based on a given property.
The object array looks something like this:
someData: [{
id: "123",
personData: [
{
personName: "John Smith",
personId: "125443",
categoryId: "B1",
description: "description"
}}]}];
I want to group the personData based on the categoryId, but represent the category grouping by its categoryName (instead of Id as this will not make much sense to the user).
There are a series of categories which are contained in a json in the following format:
const groups = {
data: [
{
categoryName: "Banking",
categoryId: "B1",
description: "Financial sector"
},
{
categoryName: "Retail",
categoryId: "R1",
description: "Retail and customer experience"
}
]
};
How would I go about filtering based on these conditions? All help is much appreciated! I am using react and typescript
Once filtered the data should look like this:
Banking
personName: John Smith
personId: 125443
Retail
personName: Judie Smith
personId: 124938
You can try groupBy on that person data.
const products = [
{ name: 'apples', category: 'fruits' },
{ name: 'oranges', category: 'fruits' },
{ name: 'potatoes', category: 'vegetables' }
];
const groupByCategory = products.groupBy(product => {
return product.category;
});
console.log(groupByCategory);
// {
// 'fruits': [
// { name: 'apples', category: 'fruits' },
// { name: 'oranges', category: 'fruits' },
// ],
// 'vegetables': [
// { name: 'potatoes', category: 'vegetables' }
// ]
// }
I think something along the lines of this function would return what you need.
const data = [
{
categoryName: "Banking",
categoryId: "B1",
description: "Financial sector"
},
{
categoryName: "Retail",
categoryId: "R1",
description: "Retail and customer experience"
}
];
function groupByProperty(arrayOfObjects, property) {
return arrayOfObjects.reduce((acc, curr) => {
const key = curr[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(curr);
return acc;
}, {});
}
const dataByCategoryName = groupByProperty(data, "categoryName");
console.log(dataByCategoryName);
/* Output
{
Banking: [{
categoryId: "B1",
categoryName: "Banking",
description: "Financial sector"
}],
Retail: [{
categoryId: "R1",
categoryName: "Retail",
description: "Retail and customer experience"
}]
}
*/

Filter array object with an other array

I want to display project that filter on skills array, for example, if I select "HTML", show me, all project with "HTML" in the project array skills. And if I select two skills, display the project that have two skills.
I have this data for my project:
const data = [
{
id: "1",
name: "project1",
techno: ["JAVASCRIPT", "REACTJS"],
imageUrl: "link",
},
{
id: "2",
name: "project2",
techno: ["HTML", "CSS", "SASS"],
imageUrl: "link",
},
{
id: "3",
name: "project3",
techno: ["JAVASCRIPT", "HTML"],
imageUrl: "link",
}
];
And my arrayFilter
const filter = ["JAVASCRIPT", "HTML", "CSS"];
For the moment, I have this code :
data
.filter((filter) => filter.techno.includes(filter[0]))
.map(({ id, ...otherProps }) => (
<ProjectItem key={id} {...otherProps} />
))
Thank you for your help
You can use every
const data = [
{
id: '1',
name: 'project1',
techno: ['JAVASCRIPT', 'REACTJS'],
imageUrl: 'link',
},
{
id: '2',
name: 'project2',
techno: ['HTML', 'CSS', 'SASS'],
imageUrl: 'link',
},
{
id: '3',
name: 'project3',
techno: ['JAVASCRIPT', 'HTML', 'REACTJS'],
imageUrl: 'link',
},
];
const filter = ['JAVASCRIPT', 'REACTJS'];
const result = data.filter(d => filter.every(t => d.techno.includes(t)));
console.log(result);

Merge several objects into one object and combine properties JavaScript

I have multiple objects inside an array, I want to merge all the objects that has the same id, but I want to combine all the values from one property as well (In this case, channels)
This is the code:
defaultArray = [
{
id: "FirstId",
name: "Some random name"
channels: [{
id: "Channel-ASD",
name: "Channel ASD"
}]
},
{
id: "FirstId",
name: "Some random name"
channels: [{
id: "Channel-QWE",
name: "Channel QWE"
}]
},
{
id: "SecondId",
name: "Some random name"
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
];
Expected output:
newArray = [
{
id: "FirstId",
name: "Some random name"
channels: [
{
id: "Channel-ASD",
name: "Channel ASD"
},
{
id: "Channel-QWE",
name: "Channel QWE"
}
]
},
{
id: "SecondId",
name: "Some random name"
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
]
You need to study about filter, map, reduce, some, ...
let defaultArray = [
{
id: "FirstId",
name: "Some random name",
channels: [{
id: "Channel-ASD",
name: "Channel ASD"
}]
},
{
id: "FirstId",
name: "Some random name",
channels: [{
id: "Channel-QWE",
name: "Channel QWE"
}]
},
{
id: "SecondId",
name: "Some random name",
channels: [{
id: "Channel-QAZ",
name: "Channel QAZ"
}]
}
];
let transformed= defaultArray.reduce((result, item, index, original)=>{
if (result.some(i=>i.id===item.id)) return result;
let channels = original.reduce((r,i)=>{
i.id===item.id && (r=[...r, ...i.channels]);
return r;
},[]);
result.push({
...item,
channels
});
return result;
},[]);
console.log(JSON.stringify(transformed,null,2));

How to Structure This array, Separate Category and Product

I have single array, I want to separate category and category Product
const product = [{
id: 1,
name: 'Cloth',
cat: ['fashion', 'man', 'women']
}, {
id: 2,
name: 'Shoes',
cat: ['fashion']
}, {
id: 3,
name: "hat",
cat: ['man', 'fashion']
}]
How to Separate category value from Product array.
const cat = ['fashion','man','women']
How to Separate category and Product
const result = [{
cat: 'fashion',
[{
id: 1,
name: 'Cloth'
}, {
id: 2,
name: 'Shoes'
}, {
id: 3,
name: "hat"
}]
}, {
cat: 'man',
[{
id: 1,
name: 'Cloth'
}, {
d: 3,
name: "hat"
}]
}, {
cat: 'women',
[{
id: 1,
name: 'Cloth'
}]
}]
How to develop this type of array please help me. Any one know please help me, Advance tanks for reply
First answer:
let categories = [];
const product = [
{ id: 1, name: "Cloth", cat: ["fashion", "man", "women"] },
{ id: 2, name: "Shoes", cat: ["fashion"] },
{ id: 3, name: "hat", cat: ["man", "fashion"] }
];
product.forEach((p) => {
p.cat.forEach((cat) => {
if(!categories.includes(cat)) {
categories.push(cat)
}
})
})
console.log(categories) // ['fashion','man','women']
If you one to get All categories from product Array.
let allCategories = [];
product.forEach(p => {
allCategories.push(...p.cat);
});
allCategories = [...new Set(allCategories)];
For second question I will use the result of first question:
allCategories.forEach(categorie => {
result.push(
{
cat: categorie,
products : product.filter(p => {
if(p.cat.includes(categorie)) {
return {
id : p.id,
name : p.name
}
}
})
}
)
})

Categories

Resources