How to add key in a nested array of Objects based on another object - javascript

I have an array of Objects named results and have the Object which key is the key value of editKeyValues object and value needs to be add in edit key. Below is the Input
var result = [{
name : 'database',
checked : true,
key : 1,
schemas : [
{
name : "schema2",
checked : true,
key : 6,
tables : [
{
name : "table2",
checked : true,
key : 7,
columns : [
{
name : "column1",
checked : true,
key : 8,
}
]
},
]
},
]
}]
var editKeyValues = { 8 : "column4", 6 : "schema4"}
Output that i want in a below format
var result = [{
name : 'database',
checked : true,
key : 1,
schemas : [
{
name : "schema2",
checked : true,
key : 6,
edit : "schema4"
tables : [
{
name : "table2",
checked : true,
key : 7,
columns : [
{
name : "column1",
checked : true,
key : 8,
edit : "column4" // value of key 8 from editkeyValues array
}
]
},
]
},]}]
Provide me a best approach because there is large amount of data in results Object... Is recursion a good idea ??? Help me to find out the best approach.

let data = [{
name: 'database',
checked: true,
key: 1,
schemas: [
{
name: "schema2",
checked: true,
key: 6,
tables: [
{
name: "table2",
checked: true,
key: 7,
columns: [
{
name: "column1",
checked: true,
key: 8,
}
]
},
]
},
]
}];
let schemas = data.flatMap(d => d.schemas);
let tables = schemas.flatMap(s => s.tables);
let columns = tables.flatMap(t => t.columns);
let flatData = [data, schemas, tables, columns].flat();
let editKeyValues = {8: "column4", 6: "schema4"};
Object.entries(editKeyValues).forEach(([key, newName]) =>
flatData.find(obj => obj.key === parseInt(key)).edit = newName);
console.log(data);

const data = [
{
id: 13,
product_name: 'Onion Pizza',
image: '26238.jpg',
category: {
id: 1,
name: 'Restaurants',
image: 'restaurant.png',
created_at: '2022-02-02T07:59:05.000000Z',
updated_at: '2022-02-15T10:58:49.000000Z',
},
status: '1',
created_at: '2022-02-19T12:22:09.000000Z',
updated_at: '2022-03-02T09:43:53.000000Z',
add_in_cart: false,
quantity_in_cart: 0,
add_in_wishlist: false,
variant: [
{
id: 34,
price: 140,
quantity: 10,
weight: '7 inch',
discount: 20,
product_id: 13,
created_at: '2022-03-02T12:46:06.000000Z',
updated_at: '2022-03-02T12:46:06.000000Z',
},
{
id: 35,
price: 350,
quantity: 5,
weight: '14 inch',
discount: 20,
product_id: 13,
created_at: '2022-03-02T12:46:06.000000Z',
updated_at: '2022-03-02T12:46:06.000000Z',
},
],
},
{
id: 15,
product_name: 'Veg Fresh Pizza',
image: '816404.jpg',
category: {
id: 1,
name: 'Restaurants',
image: 'restaurant.png',
created_at: '2022-02-02T07:59:05.000000Z',
updated_at: '2022-02-15T10:58:49.000000Z',
},
status: '1',
created_at: '2022-03-01T12:40:15.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
add_in_cart: false,
quantity_in_cart: 0,
add_in_wishlist: false,
variant: [
{
id: 30,
price: 129,
quantity: 1,
weight: '7 inch',
discount: 20,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
{
id: 31,
price: 200,
quantity: 1,
weight: '12 inch',
discount: 25,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
{
id: 32,
price: 500,
quantity: 1,
weight: '18 inch',
discount: 40,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
{
id: 33,
price: 700,
quantity: 1,
weight: '20 inch',
discount: 30,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
],
},
];
let i = 0;
let j = 0;
for (i; i < data.length; i++) {
for (j; j < data[i].variant.length; j++) {
data[i].variant.forEach(e => {
e.myKey = 0;
});
}
}
console.log('data : ' + JSON.stringify(data));
const data = [
{
id: 13,
product_name: 'Onion Pizza',
image: '26238.jpg',
category: {
id: 1,
name: 'Restaurants',
image: 'restaurant.png',
created_at: '2022-02-02T07:59:05.000000Z',
updated_at: '2022-02-15T10:58:49.000000Z',
},
status: '1',
created_at: '2022-02-19T12:22:09.000000Z',
updated_at: '2022-03-02T09:43:53.000000Z',
add_in_cart: false,
quantity_in_cart: 0,
add_in_wishlist: false,
variant: [
{
id: 34,
price: 140,
quantity: 10,
weight: '7 inch',
discount: 20,
product_id: 13,
created_at: '2022-03-02T12:46:06.000000Z',
updated_at: '2022-03-02T12:46:06.000000Z',
},
{
id: 35,
price: 350,
quantity: 5,
weight: '14 inch',
discount: 20,
product_id: 13,
created_at: '2022-03-02T12:46:06.000000Z',
updated_at: '2022-03-02T12:46:06.000000Z',
},
],
},
{
id: 15,
product_name: 'Veg Fresh Pizza',
image: '816404.jpg',
category: {
id: 1,
name: 'Restaurants',
image: 'restaurant.png',
created_at: '2022-02-02T07:59:05.000000Z',
updated_at: '2022-02-15T10:58:49.000000Z',
},
status: '1',
created_at: '2022-03-01T12:40:15.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
add_in_cart: false,
quantity_in_cart: 0,
add_in_wishlist: false,
variant: [
{
id: 30,
price: 129,
quantity: 1,
weight: '7 inch',
discount: 20,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
{
id: 31,
price: 200,
quantity: 1,
weight: '12 inch',
discount: 25,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
{
id: 32,
price: 500,
quantity: 1,
weight: '18 inch',
discount: 40,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
{
id: 33,
price: 700,
quantity: 1,
weight: '20 inch',
discount: 30,
product_id: 15,
created_at: '2022-03-02T12:27:28.000000Z',
updated_at: '2022-03-02T12:27:28.000000Z',
},
],
},
];
let i = 0;
let j = 0;
for (i; i < data.length; i++) {
for (j; j < data[i].variant.length; j++) {
data[i].variant.forEach(e => {
e.myKey = 0;
});
}
}
console.log('data : ' + JSON.stringify(data));

You could take a Map and iterate the objects and seach for nested array.
This approach uses a short circuit if no more nodes are eligible for update.
function update(array, nodes) {
return array.some(o => {
var key = o.key.toString();
if (nodes.has(key)) {
o.edit = nodes.get(key);
nodes.delete(key);
if (!nodes.size) return true;
}
return update(Object.values(o).find(Array.isArray) || [], nodes);
});
}
var data = [{ name: 'database', checked: true, key: 1, schemas: [{ name: "schema1", checked: true, key: 2, tables: [{ name: "table1", checked: true, key: 3, columns: [{ name: "column2", checked: true, key: 5 }] }] }, { name: "schema2", checked: true, key: 6, tables: [{ name: "table2", checked: true, key: 7, columns: [{ name: "column1", checked: true, key: 8 }] }] }] }],
keyValues = { 8: 'column4', 6: 'schema4' };
update(data, new Map(Object.entries(keyValues)));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Sort Nested Javascript

const list= [
{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [{ id: 1, amount: 15, dueDate: '2021-09-01' },{ id: 2,
amount: 5, dueDate: '2021-03-01' }],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [{ id: 1, amount: 20, dueDate: '2021-11-01' },{ id: 2,
amount: 24, dueDate: '2021-09-01' },{ id: 3, amount: 1, dueDate:
'2021-10-01' }],
},
{ id: 3, amount: 10, dueDate: '2021-08-01' },
{ id: 4, amount: 30, dueDate: '2021-06-01', splits: [{ id: 1, amount: 30, dueDate: '2021-01-01' }] },
{ id: 5, amount: 15, dueDate: '2021-04-01' },
];
I want to write function that sorts a list of invoices by due date (ascending) and returns a list of object containing the invoice id with below conditions:
1- For invoices with splits, sort by earliest split's due date,or invoice 1
(id: 1) the earliest would be split 2 (id: 2).
2- For invoices without splits, the earliest dueDate is the top-level due date.
Expected sorted invoices: [{"id": 4}, {"id": 1}, {"id": 5}, {"id": 3}, {"id": 2}]
function sortFun(a,b){
if(a.splits){
a = a.splits.sort(sortFun)[0]
}
if(b.splits){
b = b.splits.sort(sortFun)[0]
}
return new Date(a.dueDate) - new Date(b.dueDate)
}
let result = list.sort(sortFun).map(x=>({id:x.id}));
console.log(result)
const list = [{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [{
id: 1,
amount: 15,
dueDate: '2021-09-01'
}, {
id: 2,
amount: 5,
dueDate: '2021-03-01'
}],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [{
id: 1,
amount: 20,
dueDate: '2021-11-01'
}, {
id: 2,
amount: 24,
dueDate: '2021-09-01'
}, {
id: 3,
amount: 1,
dueDate: '2021-10-01'
}],
},
{
id: 3,
amount: 10,
dueDate: '2021-08-01'
},
{
id: 4,
amount: 30,
dueDate: '2021-06-01',
splits: [{
id: 1,
amount: 30,
dueDate: '2021-01-01'
}]
},
{
id: 5,
amount: 15,
dueDate: '2021-04-01'
},
];
function sortFun(a,b){
if(a.splits){
a = a.splits.sort(sortFun)[0]
}
if(b.splits){
b = b.splits.sort(sortFun)[0]
}
return new Date(a.dueDate) - new Date(b.dueDate)
}
let result = list.sort(sortFun).map(x=>({id:x.id}));
console.log(result)
You could do something like:
list.sort((prev, next) => {
let prevDueDate = prev.splits ? prev.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : prev.dueDate;
let nextDueDate = next.splits ? next.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : next.dueDate;
return prevDueDate.localeCompare(nextDueDate);
}).map(el => ({ id: el.id }));
See these references for more help:
MDN - Array.prototype.sort()
MDN - String.prototype.localeCompare()
const list= [
{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [{ id: 1, amount: 15, dueDate: '2021-09-01' },{ id: 2,
amount: 5, dueDate: '2021-03-01' }],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [{ id: 1, amount: 20, dueDate: '2021-11-01' },{ id: 2,
amount: 24, dueDate: '2021-09-01' },{ id: 3, amount: 1, dueDate:
'2021-10-01' }],
},
{ id: 3, amount: 10, dueDate: '2021-08-01' },
{ id: 4, amount: 30, dueDate: '2021-06-01', splits: [{ id: 1, amount: 30, dueDate: '2021-01-01' }] },
{ id: 5, amount: 15, dueDate: '2021-04-01' },
];
let res = list.sort((prev, next) => {
let prevDueDate = prev.splits ? prev.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : prev.dueDate;
let nextDueDate = next.splits ? next.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : next.dueDate;
return prevDueDate.localeCompare(nextDueDate);
}).map(el => ({ id: el.id }));
console.log(res);
Hope this is the solution that you are looking for.
const list = [
{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [
{ id: 1, amount: 15, dueDate: '2021-09-01' },
{ id: 2, amount: 5, dueDate: '2021-03-01' }
],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [
{ id: 1, amount: 20, dueDate: '2021-11-01' },
{ id: 2, amount: 24, dueDate: '2021-09-01' },
{ id: 3, amount: 1, dueDate: '2021-10-01' }
],
},
{
id: 3,
amount: 10,
dueDate: '2021-08-01'
},
{
id: 4,
amount: 30,
dueDate: '2021-06-01',
splits: [{ id: 1, amount: 30, dueDate: '2021-01-01' }]
},
{
id: 5,
amount: 15,
dueDate: '2021-04-01'
},
];
const getDateForObj = (obj) => {
if (obj.splits) {
const dateList = obj.splits.map((split) => split.dueDate);
const smallestDate = dateList.sort((a, b) => new Date(a) - new Date(b))[0];
return smallestDate;
} else {
return obj.dueDate
}
}
const newList = list.sort((a, b) =>{
const aDate = getDateForObj(a);
const bDate = getDateForObj(b);
return new Date(aDate) - new Date(bDate);
});
console.log(newList);

javascript 2D array vlaue exchange

I would like to compare two arrays and replace the array value with the same property value.
let first_array =[{ model: 'aa', size: '85(XS)', count: 200, number: '10-2' },{ model: 'bb', size: '105(XL)', count: 150, number: '' },{ model: 'cc', size: '95(M)', count: 100, number: '9-2' },{ model: 'dd', size: '85(XS)', count: 50, number: '' }]
let second_array = [{ model: 'aa', size: '85(XS)', count: 1, number: '' },{ model: 'bb', size: '105(XL)', count: 1, number: '' },{ model: 'cc', size: '95(M)', count: 2, number: '' },{ model: 'dd', size: '85(S)', count: 3, number: '' },{ model: 'dd', size: '80(XS)', count: , number: '' }]
Assuming there are two array.
Comparing the 'a' and 'b' arrays, the same 'size' as the 'model' inserts the count value of the 'a' array into the count value of the 'b' array, and the wrong one is marked as null.
And this is what I want.
let vlaue = [{ model: 'aa', size: '85(XS)', count: 200, number: '10-2' },{ model: 'bb', size: '105(XL)', count: 150, number: '' },{ model: 'cc', size: '95(M)', count: 100, number: '9-2' },{ model: 'dd', size: '85(XS)', count: 50, number: '' }]
That's the code I tried.
for (var j = 0; j<second_array.length;j++){
for(var i = 0; i < first_array.length ;i++){
var count = false
if(second_array[j]["model"]+second_array[j]["size"] === first_array[i]){
count = true
}else{
count = false
}
if(count == true){
if(objectdata[first_array[i]]["count"] === 0){
second_array[j]["count"] = ""
second_array[j]["number"] = ""
}else{
second_array[j]["count"] = objectdata[first_array[i]]["count"];
second_array[j]["number"] = objectdata[first_array[i]]["number"];
}
break
}else{
second_array[j]["count"] = ""
second_array[j]["number"] = ""
}
}
}
let first_array =[{ model: 'aa', size: '85(XS)', count: 200, number: '10-2' },{ model: 'bb', size: '105(XL)', count: 150, number: '' },{ model: 'cc', size: '95(M)', count: 100, number: '9-2' },{ model: 'dd', size: '85(XS)', count: 50, number: '' }]
let second_array = [{ model: 'aa', size: '85(XS)', count: 1, number: '' },{ model: 'bb', size: '105(XL)', count: 1, number: '' },{ model: 'cc', size: '95(M)', count: 2, number: '' },{ model: 'dd', size: '85(S)', count: 3, number: '1' }]
let value=[];
for(let i = 0 ; i<first_array.length ; i++){
value.push({
name:first_array[i].model ? first_array[i].model :second_array[i].model,
size: first_array[i].size ?first_array[i].size :second_array[i].size,
count: first_array[i].count ?first_array[i].count :second_array[i].count,
number: first_array[i].number ?first_array[i].number :second_array[i].number,
})
}
console.log(value)
let first_array =[{ model: 'aa', size: '85(XS)', count: 200, number: '10-2' },{ model: 'bb', size: '105(XL)', count: 150, number: '' },{ model: 'cc', size: '95(M)', count: 100, number: '9-2' },{ model: 'dd', size: '85(XS)', count: 50, number: '' }]
let second_array = [{ model: 'aa', size: '85(XS)', count: 1, number: '' },{ model: 'bb', size: '105(XL)', count: 1, number: '' },{ model: 'cc', size: '95(M)', count: 2, number: '' },{ model: 'dd', size: '85(S)', count: 3, number: '1' }]
let value=[];
for(let i = 0 ; i<first_array.length ; i++){
value.push({
name:first_array[i].model ? first_array[i].model :second_array[i].model,
size: first_array[i].size ?first_array[i].size :second_array[i].size,
count: first_array[i].count ?first_array[i].count :second_array[i].count,
number: first_array[i].number ?first_array[i].number :second_array[i].number,
})
}
console.log(value)
let first_array = [{
model: 'aa',
size: '85(XS)',
count: 200,
number: '10-2'
}, {
model: 'bb',
size: '105(XL)',
count: 150,
number: ''
}, {
model: 'cc',
size: '95(M)',
count: 100,
number: '9-2'
}, {
model: 'dd',
size: '85(XS)',
count: 50,
number: ''
}]
let second_array = [{
model: 'aa',
size: '85(XS)',
count: 1,
number: ''
}, {
model: 'bb',
size: '105(XL)',
count: 1,
number: ''
}, {
model: 'cc',
size: '95(M)',
count: 2,
number: ''
}, {
model: 'dd',
size: '85(S)',
count: 3,
number: ''
}, {
model: 'dd',
size: '80(XS)',
count: '',
number: ''
}]
let desired = [{
model: 'aa',
size: '85(XS)',
count: 200,
number: '10-2'
},
{
model: 'bb',
size: '105(XL)',
count: 150,
number: ''
},
{
model: 'cc',
size: '95(M)',
count: 100,
number: '9-2'
},
{
model: 'dd',
size: '85(XS)',
count: 50,
number: ''
}
]
const dict = second_array.reduce((map, {
model,
size,
count,
number
}) => ({
...map,
[`${model}${size}`]: {
count,
number
}
}), {})
const newArray = first_array.map(({
model,
size,
count,
number
}) => ({
model,
size,
count: count ?? dict[`${model}${size}`]?.count,
number: number ?? dict[`${model}${size}`]?.number,
}))
// output:
console.log(newArray)
// desired:
console.log(desired)
// match:
console.log(JSON.stringify(newArray) === JSON.stringify(desired))

Uncaught TypeError: collections.map is not a function in React Js

I am trying to render a Component and getting error collections.map is not a function. below is the attached file of my SHOP_DATA and CollectionOverview. I am importing data from the SHOP_DATA file and in other components it's working fine. I am also getting error like Cannot read property 'toUpperCase' of undefined.
import React, { useState } from "react";
import "./CollectionOverview.scss";
import CollectionPreview from "../CollectionPreview/CollectionPreview";
import SHOP_DATA from "../../Pages/Shop/Shop_data";
const CollectionOverview = () => {
const [collections] = useState(SHOP_DATA);
return (
<div>
{collections.map(({ id, title, items }) => (
<CollectionPreview key={id} title={title} items={items} />
))}
</div>
);
};
export default CollectionOverview;
This is my SHOP_DATA from which i am importing data to my CollectionOverview Component.
const SHOP_DATA = {
hats: {
id: 1,
title: "Hats",
routeName: "hats",
items: [
{
id: 1,
name: "Brown Brim",
imageUrl: "https://i.ibb.co/ZYW3VTp/brown-brim.png",
price: 25,
},
{
id: 2,
name: "Blue Beanie",
imageUrl: "https://i.ibb.co/ypkgK0X/blue-beanie.png",
price: 18,
},
{
id: 3,
name: "Brown Cowboy",
imageUrl: "https://i.ibb.co/QdJwgmp/brown-cowboy.png",
price: 35,
},
{
id: 4,
name: "Grey Brim",
imageUrl: "https://i.ibb.co/RjBLWxB/grey-brim.png",
price: 25,
},
{
id: 5,
name: "Green Beanie",
imageUrl: "https://i.ibb.co/YTjW3vF/green-beanie.png",
price: 18,
},
{
id: 6,
name: "Palm Tree Cap",
imageUrl: "https://i.ibb.co/rKBDvJX/palm-tree-cap.png",
price: 14,
},
{
id: 7,
name: "Red Beanie",
imageUrl: "https://i.ibb.co/bLB646Z/red-beanie.png",
price: 18,
},
{
id: 8,
name: "Wolf Cap",
imageUrl: "https://i.ibb.co/1f2nWMM/wolf-cap.png",
price: 14,
},
{
id: 9,
name: "Blue Snapback",
imageUrl: "https://i.ibb.co/X2VJP2W/blue-snapback.png",
price: 16,
},
],
},
sneakers: {
id: 2,
title: "Sneakers",
routeName: "sneakers",
items: [
{
id: 10,
name: "Adidas NMD",
imageUrl: "https://i.ibb.co/0s3pdnc/adidas-nmd.png",
price: 220,
},
{
id: 11,
name: "Adidas Yeezy",
imageUrl: "https://i.ibb.co/dJbG1cT/yeezy.png",
price: 280,
},
{
id: 12,
name: "Black Converse",
imageUrl: "https://i.ibb.co/bPmVXyP/black-converse.png",
price: 110,
},
{
id: 13,
name: "Nike White AirForce",
imageUrl: "https://i.ibb.co/1RcFPk0/white-nike-high-tops.png",
price: 160,
},
{
id: 14,
name: "Nike Red High Tops",
imageUrl: "https://i.ibb.co/QcvzydB/nikes-red.png",
price: 160,
},
{
id: 15,
name: "Nike Brown High Tops",
imageUrl: "https://i.ibb.co/fMTV342/nike-brown.png",
price: 160,
},
{
id: 16,
name: "Air Jordan Limited",
imageUrl: "https://i.ibb.co/w4k6Ws9/nike-funky.png",
price: 190,
},
{
id: 17,
name: "Timberlands",
imageUrl: "https://i.ibb.co/Mhh6wBg/timberlands.png",
price: 200,
},
],
},
jackets: {
id: 3,
title: "Jackets",
routeName: "jackets",
items: [
{
id: 18,
name: "Black Jean Shearling",
imageUrl: "https://i.ibb.co/XzcwL5s/black-shearling.png",
price: 125,
},
{
id: 19,
name: "Blue Jean Jacket",
imageUrl: "https://i.ibb.co/mJS6vz0/blue-jean-jacket.png",
price: 90,
},
{
id: 20,
name: "Grey Jean Jacket",
imageUrl: "https://i.ibb.co/N71k1ML/grey-jean-jacket.png",
price: 90,
},
{
id: 21,
name: "Brown Shearling",
imageUrl: "https://i.ibb.co/s96FpdP/brown-shearling.png",
price: 165,
},
{
id: 22,
name: "Tan Trench",
imageUrl: "https://i.ibb.co/M6hHc3F/brown-trench.png",
price: 185,
},
],
},
womens: {
id: 4,
title: "Womens",
routeName: "womens",
items: [
{
id: 23,
name: "Blue Tanktop",
imageUrl: "https://i.ibb.co/7CQVJNm/blue-tank.png",
price: 25,
},
{
id: 24,
name: "Floral Blouse",
imageUrl: "https://i.ibb.co/4W2DGKm/floral-blouse.png",
price: 20,
},
{
id: 25,
name: "Floral Dress",
imageUrl: "https://i.ibb.co/KV18Ysr/floral-skirt.png",
price: 80,
},
{
id: 26,
name: "Red Dots Dress",
imageUrl: "https://i.ibb.co/N3BN1bh/red-polka-dot-dress.png",
price: 80,
},
{
id: 27,
name: "Striped Sweater",
imageUrl: "https://i.ibb.co/KmSkMbH/striped-sweater.png",
price: 45,
},
{
id: 28,
name: "Yellow Track Suit",
imageUrl: "https://i.ibb.co/v1cvwNf/yellow-track-suit.png",
price: 135,
},
{
id: 29,
name: "White Blouse",
imageUrl: "https://i.ibb.co/qBcrsJg/white-vest.png",
price: 20,
},
],
},
mens: {
id: 5,
title: "Mens",
routeName: "mens",
items: [
{
id: 30,
name: "Camo Down Vest",
imageUrl: "https://i.ibb.co/xJS0T3Y/camo-vest.png",
price: 325,
},
{
id: 31,
name: "Floral T-shirt",
imageUrl: "https://i.ibb.co/qMQ75QZ/floral-shirt.png",
price: 20,
},
{
id: 32,
name: "Black & White Longsleeve",
imageUrl: "https://i.ibb.co/55z32tw/long-sleeve.png",
price: 25,
},
{
id: 33,
name: "Pink T-shirt",
imageUrl: "https://i.ibb.co/RvwnBL8/pink-shirt.png",
price: 25,
},
{
id: 34,
name: "Jean Long Sleeve",
imageUrl: "https://i.ibb.co/VpW4x5t/roll-up-jean-shirt.png",
price: 40,
},
{
id: 35,
name: "Burgundy T-shirt",
imageUrl: "https://i.ibb.co/mh3VM1f/polka-dot-shirt.png",
price: 25,
},
],
},
};
export default SHOP_DATA;
map function is not native to objects. It is used to iterate an array and it also returns an array, and you are using it on objects. This is the correct implementation.
import React, { useState } from "react";
import "./CollectionOverview.scss";
import CollectionPreview from "../CollectionPreview/CollectionPreview";
import SHOP_DATA from "../../Pages/Shop/Shop_data";
const CollectionOverview = () => {
const [collections] = useState(SHOP_DATA);
return (
<div>
{Object.values(collections).map(({ id, title, items }) => (
<CollectionPreview key={id} title={title} items={items} />
))}
</div>
);
};
export default CollectionOverview;

Filter and combine fields from 2 arrays with ES6 JavaScript?

I have 2 arrays, one of pizza details and the other is an order state. The id field is what links them. So in this example, the order has 2 x Pepperoni and 3 x Margarita.
const pizzaContent = [
{
id: 0,
name: 'Pepperoni',
price: 20,
hot: true,
stockQuantity: 3
},
{
id: 1,
name: 'Margarita',
price: 25,
stockQuantity: 3
},
{
id: 2,
name: 'Hawaiian',
price: 15,
stockQuantity: 0
}
];
const orders = [{
id: 0,
quantity: 2
},{
id: 1,
quantity: 3
}];
I'm trying to create a new array which has the quantity from orders and the fields from pizzaContent. Any pizzas which aren't in the order shouldn't be part of this array.
I've gotten close with the following:
const pizzasInOrder = this.props.orders.map(order => {
return (
{
quantity: order.quantity,
pizza: this.props.pizzas.find(pizza => {
return (
order.id === pizza.id
);
})
}
)
});
However, the result is:
pizzasInOrder = [
{
pizza: {id: 0, name: "Pepperoni", price: 20, hot: true, stockQuantity: 3},
quantity:2
},
{
pizza: {id: 1, name: "Margarita", price: 25, stockQuantity: 3},
quantity:3
}
]
But what I need is:
pizzasInOrder = [
{
id: 0, name: "Pepperoni", price: 20, hot: true, stockQuantity: 3, quantity: 2
},
{
id: 1, name: "Margarita", price: 25, stockQuantity: 3, quantity: 3
}
]
Use Object.assign and no extra keys
const pizzasInOrder = this.props.orders.map(order =>
Object.assign({quantity: order.quantity},
this.props.pizzas.find(pizza => order.id === pizza.id))
);
You can use Object.assign() to merge objects into one.
example..
const pizzaContent = [
{
id: 0,
name: 'Peperoni',
price: 20,
hot: true,
stockQuantity: 3
},
{
id: 1,
name: 'Margarita',
price: 25,
stockQuantity: 3
},
{
id: 2,
name: 'Hawian',
price: 15,
stockQuantity: 0
}
];
const orders = [{
id: 0,
quantity: 2
},{
id: 1,
quantity: 3
}];
let pizzasInOrder = orders.map((order) => {
return Object.assign(order,
pizzaContent.find(pizza => order.id === pizza.id));
});
console.log(pizzasInOrder);

How to use _.reduce or native reduce to sum and rank objects?

It seems as though the examples for _.reduce (or the equivalent native function) are very simplistic. Could someone provide an example of using this function to sum and then rank/sort an array of objects? For example, if my array contains --
[{ name: 'John', store: 23, revenue: 300.00 },
{ name: 'John', store: 23, revenue: 600.00 },
{ name: 'Kerry', store: 23, revenue: 100.00 },
{ name: 'Kerry', store: 23, revenue: 200.00 },
{ name: 'Lars', store: 24, revenue: 600.00 },
{ name: 'Lars', store: 24, revenue: 800.00 },
{ name: 'Lars', store: 24, revenue: 1000.00 },
{ name: 'Indira', store: 24, revenue: 1800.00 },
{ name: 'Indira', store: 24, revenue: 2800.00 },
{ name: 'Indira', store: 24, revenue: 3800.00 },
{ name: 'Jacinta', store: 24, revenue: 300.00 }]
And I want the output to be as follows:
[{store: 23, rank: 1, name: 'John', revenue: 900.00},
{store: 23, rank: 2, name: 'Kerry', revenue: 300.00},
{store: 24, rank: 1, name: 'Indira', revenue: 8400.00},
{store: 24, rank: 2, name: 'Lars', revenue: 2400.00},
{store: 24, rank: 3, name: 'Jacinta', revenue: 300.00}]
What's the best way to go about this?
This little monster seems to do the job:
result = _(data).chain().groupBy('name').map(function(g) {
return {
name:g[0].name,
store:g[0].store,
revenue: _.reduce(g, function(a, b) { return a + b.revenue}, 0)
}
}).sortBy('revenue').reverse().groupBy('store').map(function(g) {
return _(g).chain().map(function(x, n) {
return x.rank = n + 1, x;
}).value()
}).values().flatten().value()

Categories