I am trying to remove a specific object from a nested object:
This is the original data and the function that I am using:
const allList = [
{
"id": "listGroup",
"condition": "AND",
"data": [
{
"id": "611901",
"name": "1",
"value": "1",
"data": "6137",
"path": "Automotive Miscellaneous>Car Rental - Personal Use>Times/Last 12 Months",
"uniqueId": "pmds-dragdrop__61190158"
},
{
"id": "listGroup_1",
"children": {
"key": null,
"ref": null,
"props": {
"children": {
"type": "div",
"key": null,
"ref": null,
"props": {
"style": {
"display": "flex",
"boxSizing": "border-box"
},
"children": [
{
"type": {
"propTypes": {},
"defaultProps": {
"id": null,
"children": null,
"className": null,
"disabled": false,
"required": false,
"options": [],
"multiple": false,
"placeholder": null,
"error": null,
"onChange": null,
"display": "pillBelow",
"invert": false
},
"ComponentName": "Dropdown",
"package": "#publicismedia-ds/ui-dropdown",
"version": "2.1.0"
},
"key": null,
"ref": null,
"props": {
"options": [
{
"label": "AND",
"value": "AND"
},
{
"label": "OR",
"value": "OR"
},
{
"label": "AND NOT",
"value": "AND NOT"
},
{
"label": "OR NOT",
"value": "OR NOT"
}
],
"value": {
"label": "AND",
"value": "AND"
},
"children": " ",
"id": null,
"className": null,
"disabled": false,
"required": false,
"multiple": false,
"placeholder": null,
"error": null,
"display": "pillBelow",
"invert": false
},
"_owner": null,
"_store": {}
},
{
"type": {
"propTypes": {},
"defaultProps": {
"className": "",
"list": null,
"onChange": null,
"id": "",
"selectAll": false,
"placeholder": "Drop keys here",
"children": null,
"allowDuplicates": true,
"allowed": null,
"notAllowed": null,
"border": false,
"removeDraggedItems": true,
"reorder": true,
"deleteItem": false,
"errorMessage": "Not allowed",
"onDragStart": null,
"onDrop": null,
"__TYPE": "DragDrop"
},
"componentName": "DragDrop",
"package": "#publicismedia-ds/ui-drag-drop",
"version": "2.2.0-beta.1"
},
"key": null,
"ref": null,
"props": {
"list": {
"id": "listGroup_1",
"condition": "OR",
"data": [
{
"id": "611908",
"name": "4",
"value": "4",
"data": "432",
"path": "Automotive Miscellaneous>Car Rental - Personal Use>Times/Last 12 Months",
"uniqueId": "pmds-dragdrop__61190834"
}
]
},
"id": "listGroup_1",
"selectAll": false,
"placeholder": "Drop keys here",
"deleteItem": true,
"border": true,
"allowDuplicates": false,
"errorMessage": "Not allowed!",
"className": "",
"children": null,
"allowed": null,
"notAllowed": null,
"removeDraggedItems": true,
"reorder": true,
"onDragStart": null,
"onDrop": null,
"__TYPE": "DragDrop"
},
"_owner": null,
"_store": {}
}
]
},
"_owner": null,
"_store": {}
}
},
"_owner": null,
"_store": {}
},
"uniqueId": "pmds-dragdrop__listGroup_159"
}
]
},
{
"id": "listGroup_1",
"condition": "OR",
"data": [
{
"id": "611908",
"name": "4",
"value": "4",
"data": "432",
"path": "Automotive Miscellaneous>Car Rental - Personal Use>Times/Last 12 Months",
"uniqueId": "pmds-dragdrop__61190834"
}
]
}
]
console.log(allList);
function filterObject(obj, key) {
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (i == key) {
delete obj[key];
} else if (typeof obj[i] == "object") {
filterObject(obj[i], key);
}
}
return obj;
}
console.log(filterObject(allList, "children"));
I want to delete all objects with key "children" and I am using a recursive function called "filterObject". I have to say the function works fine.
but I would like to keep the original object too, but I don't know how can I do that. I hope that you can help me
Your Answer
const allList = [
{
"id": "listGroup",
"condition": "AND",
"data": [
{
"id": "611901",
"name": "1",
"value": "1",
"data": "6137",
"path": "Automotive Miscellaneous>Car Rental - Personal Use>Times/Last 12 Months",
"uniqueId": "pmds-dragdrop__61190158"
},
{
"id": "listGroup_1",
"children": {
"key": null,
"ref": null,
"props": {
"children": {
"type": "div",
"key": null,
"ref": null,
"props": {
"style": {
"display": "flex",
"boxSizing": "border-box"
},
"children": [
{
"type": {
"propTypes": {},
"defaultProps": {
"id": null,
"children": null,
"className": null,
"disabled": false,
"required": false,
"options": [],
"multiple": false,
"placeholder": null,
"error": null,
"onChange": null,
"display": "pillBelow",
"invert": false
},
"ComponentName": "Dropdown",
"package": "#publicismedia-ds/ui-dropdown",
"version": "2.1.0"
},
"key": null,
"ref": null,
"props": {
"options": [
{
"label": "AND",
"value": "AND"
},
{
"label": "OR",
"value": "OR"
},
{
"label": "AND NOT",
"value": "AND NOT"
},
{
"label": "OR NOT",
"value": "OR NOT"
}
],
"value": {
"label": "AND",
"value": "AND"
},
"children": " ",
"id": null,
"className": null,
"disabled": false,
"required": false,
"multiple": false,
"placeholder": null,
"error": null,
"display": "pillBelow",
"invert": false
},
"_owner": null,
"_store": {}
},
{
"type": {
"propTypes": {},
"defaultProps": {
"className": "",
"list": null,
"onChange": null,
"id": "",
"selectAll": false,
"placeholder": "Drop keys here",
"children": null,
"allowDuplicates": true,
"allowed": null,
"notAllowed": null,
"border": false,
"removeDraggedItems": true,
"reorder": true,
"deleteItem": false,
"errorMessage": "Not allowed",
"onDragStart": null,
"onDrop": null,
"__TYPE": "DragDrop"
},
"componentName": "DragDrop",
"package": "#publicismedia-ds/ui-drag-drop",
"version": "2.2.0-beta.1"
},
"key": null,
"ref": null,
"props": {
"list": {
"id": "listGroup_1",
"condition": "OR",
"data": [
{
"id": "611908",
"name": "4",
"value": "4",
"data": "432",
"path": "Automotive Miscellaneous>Car Rental - Personal Use>Times/Last 12 Months",
"uniqueId": "pmds-dragdrop__61190834"
}
]
},
"id": "listGroup_1",
"selectAll": false,
"placeholder": "Drop keys here",
"deleteItem": true,
"border": true,
"allowDuplicates": false,
"errorMessage": "Not allowed!",
"className": "",
"children": null,
"allowed": null,
"notAllowed": null,
"removeDraggedItems": true,
"reorder": true,
"onDragStart": null,
"onDrop": null,
"__TYPE": "DragDrop"
},
"_owner": null,
"_store": {}
}
]
},
"_owner": null,
"_store": {}
}
},
"_owner": null,
"_store": {}
},
"uniqueId": "pmds-dragdrop__listGroup_159"
}
]
},
{
"id": "listGroup_1",
"condition": "OR",
"data": [
{
"id": "611908",
"name": "4",
"value": "4",
"data": "432",
"path": "Automotive Miscellaneous>Car Rental - Personal Use>Times/Last 12 Months",
"uniqueId": "pmds-dragdrop__61190834"
}
]
}
]
function filterObject(obj, key) {
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (i == key) {
delete obj[key];
} else if (typeof obj[i] == "object") {
filterObject(obj[i], key);
}
}
return obj;
}
const filtered = filterObject(JSON.parse(JSON.stringify(allList)), "children")
console.log(filtered)
console.log(allList);
What You are doing
const arr = [1,2,3];
const arr2 = arr.reverse();
console.log(arr);
console.log(arr2)
What You need
You have to copy the array not reference the array
const arr = [1,2,3];
const arr2 = [...arr].reverse();
console.log(arr);
console.log(arr2)
But in your case it's not gonna work why
because spread operators create a shallow copy mean all the deep objects are connected between copied array and original array
Method 2
const arr = [1,2,3];
const arr2 = JSON.parse(JSON.stringify(arr)).reverse();
console.log(arr);
console.log(arr2)
Related
Apologies if there is already an answer for this, I've been unable to locate one that has worked for me.
I have defined a menu system for React where the information is stored in an array of objects. Each object has the posibility of having sub items (objects in another array) and I'm looking to filter the entire menu for values.
Menu Object
[
{
"key": "Dashboard",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"title": "Dashboard",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/",
"children": "Dashboard"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Clients",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Clients",
"submenus": [
{
"key": "Clients.Add",
"title": "Create Client",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Clients/create",
"children": "Create Client"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Clients.List",
"title": "List Clients",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Clients/",
"children": "List Clients"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Clients.Search",
"title": "Search Clients",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Clients/search",
"children": "Search Clients"
},
"_owner": null,
"_store": {}
}
}
]
},
{
"key": "Contractors",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Contractors",
"submenus": [
{
"key": "Contractors.Add",
"title": "Create Contractor",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Contractors/create",
"children": "Create Contractor"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Contractors.List",
"title": "List Contractors",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Contractors/",
"children": "List Contractors"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Contractors.Search",
"title": "Search Contractors",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Contractors/search",
"children": "Search Contractors"
},
"_owner": null,
"_store": {}
}
}
]
},
{
"key": "Jobs",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Jobs",
"submenus": [
{
"key": "Jobs.Add",
"title": "Create Job",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Jobs/create",
"children": "Create Job"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Jobs.List",
"title": "List Jobs",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Jobs/",
"children": "List Jobs"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Jobs.Search",
"title": "Search Jobs",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Jobs/search",
"children": "Search Jobs"
},
"_owner": null,
"_store": {}
}
}
]
},
{
"isDivider": true
},
{
"key": "Config",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Configuration",
"submenus": [
{
"key": "Config.Category.Add",
"title": "Create Category",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Category/create",
"children": "Create Category"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Category.List",
"title": "List Categories",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Category/",
"children": "List Categories"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Specialist.Add",
"title": "Create Specialist",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Specialist/create",
"children": "Create Specialist"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Specialist.List",
"title": "List Specialists",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Specialist/",
"children": "List Specialists"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Status.Add",
"title": "Create Status",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Status/create",
"children": "Create Status"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Status.List",
"title": "List Statuses",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Status/",
"children": "List Statuses"
},
"_owner": null,
"_store": {}
}
}
]
},
{
"key": "UserManagement",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "User Management",
"submenus": [
{
"key": "UserManagement.Add",
"title": "Create User",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/UserManagement/create",
"children": "Create User"
},
"_owner": null,
"_store": {}
}
},
{
"key": "UserManagement.List",
"title": "List Users",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/UserManagement/",
"children": "List Users"
},
"_owner": null,
"_store": {}
}
}
]
},
{
"isDivider": true
},
{
"key": "LockScreen",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"title": "Lock Screen",
"component": "Lock Screen"
}
]
So if I were to filter this on title for the value "list" it should return back
[
{
"key": "Clients",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Clients",
"submenus": [
{
"key": "Clients.List",
"title": "List Clients",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Clients/",
"children": "List Clients"
},
"_owner": null,
"_store": {}
}
}
]
},
{
"key": "Contractors",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Contractors",
"submenus": [
{
"key": "Contractors.List",
"title": "List Contractors",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Contractors/",
"children": "List Contractors"
},
"_owner": null,
"_store": {}
}
},
]
},
{
"key": "Jobs",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Jobs",
"submenus": [
{
"key": "Jobs.List",
"title": "List Jobs",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Jobs/",
"children": "List Jobs"
},
"_owner": null,
"_store": {}
}
},
]
},
{
"key": "Config",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "Configuration",
"submenus": [
{
"key": "Config.Category.List",
"title": "List Categories",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Category/",
"children": "List Categories"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Specialist.List",
"title": "List Specialists",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Specialist/",
"children": "List Specialists"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Status.List",
"title": "List Statuses",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Status/",
"children": "List Statuses"
},
"_owner": null,
"_store": {}
}
}
]
},
{
"key": "UserManagement",
"icon": {
"type": {},
"key": null,
"ref": null,
"props": {},
"_owner": null,
"_store": {}
},
"isSubMenu": true,
"title": "User Management",
"submenus": [
{
"key": "UserManagement.List",
"title": "List Users",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/UserManagement/",
"children": "List Users"
},
"_owner": null,
"_store": {}
}
}
]
}
]
Or it should return back
[
{
"key": "Clients.List",
"title": "List Clients",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Clients/",
"children": "List Clients"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Contractors.List",
"title": "List Contractors",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Contractors/",
"children": "List Contractors"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Jobs.List",
"title": "List Jobs",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Jobs/",
"children": "List Jobs"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Category.List",
"title": "List Categories",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Category/",
"children": "List Categories"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Specialist.List",
"title": "List Specialists",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Specialist/",
"children": "List Specialists"
},
"_owner": null,
"_store": {}
}
},
{
"key": "Config.Status.List",
"title": "List Statuses",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/Config/Status/",
"children": "List Statuses"
},
"_owner": null,
"_store": {}
}
},
{
"key": "UserManagement.List",
"title": "List Users",
"component": {
"type": {},
"key": null,
"ref": null,
"props": {
"to": "/admin/UserManagement/",
"children": "List Users"
},
"_owner": null,
"_store": {}
}
}
]
At present I have the following which works for the 1st level objects, but the sub menu's all get returned:
const MenuSearch = (value) => {
const SearchTerm = value.toLowerCase();
console.log(SearchTerm, MenuItems);
if (!value || value.length < 1){
// show all menu items
SetMenuItemsFiltered(MenuItems);
} else {
let temp = [...MenuItems];
SetMenuItemsFiltered(temp.filter((MenuItem) => {
if (!MenuItem.isSubMenu && !MenuItem.isDivider){
return MenuItem.title.toLowerCase().includes(SearchTerm);
} else if (MenuItem.isSubMenu){
return MenuItem.submenus.filter((SubMenuItem) => {
const SubMenuItemLabel = SubMenuItem.title.toLowerCase();
console.log(SubMenuItemLabel, SearchTerm, SubMenuItemLabel.includes(SearchTerm))
return SubMenuItemLabel.includes(SearchTerm.toLowerCase());
})
}
}));
}
}
The ~ in !~value.length is just my preferred way to say "don't start from -1 and consider it 0"
const MenuSearch = (value) => {
const searchWord = value.toLowerCase();
if (!value || !~value.length) {
// early return.
return SetMenuItemsFiltered(MenuItems);
}
const result = data.reduce((prev, curr) => {
const title = curr.title?.toLowerCase();
if (!curr.submenus && !curr.isDivider) {
if (title.includes(searchWord)) {
return prev.concat(curr);
}
}
if (curr.isSubMenu) {
return prev.concat(
curr.submenus.filter((item) =>
item.title.toLowerCase().includes(searchWord)
),
);
}
return prev;
}, []);
SetMenuItemsFiltered(result);
};
I think this is what you're looking for:
const objectsFilter = require("objectsfilter");
const data = require("./data.json");
const MenuSearch = (value) => {
const searchWord = value.toLowerCase();
if (!value || !~value.length) {
// early return.
return SetMenuItemsFiltered(MenuItems);
}
const result = data.reduce((prev, curr) => {
const title = curr.title?.toLowerCase();
if (!curr.submenus && !curr.isDivider) {
if (title.includes(searchWord)) {
return prev.concat(curr);
}
}
if (curr.isSubMenu) {
const submenus = [];
objectsFilter.objectsForEach(curr, (currentItem, key) => {
if (key === "submenus") {
submenus.push(
currentItem.filter((item) =>
item.title.toLowerCase().includes(searchWord)
),
);
}
});
return prev.concat({
...curr,
submenus,
});
}
return prev;
}, []);
SetMenuItemsFiltered(result);
};
Objectsfilter: https://github.com/Meno-101/objectsfilter
npm: https://www.npmjs.com/package/objectsfilter
The issue is that you are filtering the MenuItem.submenus but not storing the values filtered. Instead, you are just returning the whole MenuItem.submenu
So It should be
MenuItem.submenus= MenuItem.submenus.filter((SubMenuItem) => {
const SubMenuItemLabel = SubMenuItem.title.toLowerCase();
return SubMenuItemLabel.includes(SearchTerm.toLowerCase());
})
and return true if MenuItem.submenus.length>0.
So final code would be
temp.filter((MenuItem) => {
if (!MenuItem.isSubMenu && !MenuItem.isDivider){
return MenuItem.title.toLowerCase().includes(SearchTerm);
} else if (MenuItem.isSubMenu){
MenuItem.submenus= MenuItem.submenus.filter((SubMenuItem) => {
const SubMenuItemLabel = SubMenuItem.title.toLowerCase();
console.log(SubMenuItemLabel, SearchTerm,
SubMenuItemLabel.includes(SearchTerm))
return SubMenuItemLabel.includes(SearchTerm.toLowerCase());
})
return MenuItem.submenus.length;
}
})
I ended up taking a different approach with this, rather than returning on the filter I would use the filter to create a new array of objects that matched. I've posted the answer here but will continue to check if anyone comes up with a better solution.
const MenuSearch = (value) => {
const SearchTerm = value.toLowerCase();
if (!value || value.length < 1){
// show all menu items
SetMenuItemsFiltered(MenuItems);
} else {
let FilteredItems = [];
// filter the data
MenuItems.filter((MenuItem) => {
if (!MenuItem.isSubMenu && !MenuItem.isDivider){
if (MenuItem.title.toLowerCase().includes(SearchTerm)){
FilteredItems.push(MenuItem);
}
//return MenuItem.title.toLowerCase().includes(SearchTerm);
} else if (MenuItem.isSubMenu){
MenuItem.submenus.filter((SubMenuItem) => {
const SubMenuItemLabel = SubMenuItem.title.toLowerCase();
// return SubMenuItemLabel.includes(SearchTerm);
if (SubMenuItemLabel.includes(SearchTerm)){
FilteredItems.push(SubMenuItem);
}
})
}
});
SetMenuItemsFiltered(FilteredItems);
}
}
I'm currently working on a personal project, which is an E-Commerce Web App. To do this, I used the Commerce.js library and is currently hitting a roadblock. Although technically I can do this by using nested for loops, I would like to look for a more efficient method that uses cleaner code and is faster and more efficient with resources.
The Commerce.js documentation does not return the products in a certain category, therefore I have to use two functions to get them seperately.
const commerce = new Commerce(process.env.REACT_APP_API_KEY)
var shopItems;
var categoriesList;
useEffect(()=> {
commerce.categories.list().then((categories) => {
categoriesList = categories;
console.log(categoriesList.data)
});
commerce.products.list().then((product) => {
shopItems = product;
console.log(shopItems.data)
});
})
DATA
Categories:
{
"id": "cat_O3bR5XyEklnzdj",
"parent_id": null,
"slug": "new-releases",
"name": "New Releases",
"description": null,
"products": 1,
"created": 1639555008,
"updated": 1639555008,
"meta": null,
"assets": [
{
"id": "ast_Op1YoVxzaglXLv",
"url": "https://cdn.chec.io/merchants/37076/assets/aHVfA98RM9vVKjMa|Screenshot (6).png",
"description": null,
"is_image": true,
"filename": "Screenshot (6).png",
"file_size": 933236,
"file_extension": "png",
"image_dimensions": {
"width": 1920,
"height": 1080
},
"meta": [],
"created_at": 1639555026,
"updated_at": 1639555031
}
],
"children": []
}
Products:
[
{
"id": "prod_RyWOwmdx1GlnEa",
"created": 1639554903,
"updated": 1639554964,
"active": true,
"permalink": "tE45fb",
"name": "Air Jordan 11 Cool Grey",
"description": "<p></p>",
"price": {
"raw": 300000,
"formatted": "300,000.00",
"formatted_with_symbol": "Rp300,000.00",
"formatted_with_code": "300,000.00 IDR"
},
"inventory": {
"managed": false,
"available": 0
},
"sku": null,
"sort_order": 0,
"seo": {
"title": null,
"description": null
},
"thank_you_url": null,
"meta": null,
"conditionals": {
"is_active": true,
"is_tax_exempt": false,
"is_pay_what_you_want": false,
"is_inventory_managed": false,
"is_sold_out": false,
"has_digital_delivery": false,
"has_physical_delivery": false,
"has_images": true,
"collects_fullname": false,
"collects_shipping_address": false,
"collects_billing_address": false,
"collects_extra_fields": false
},
"is": {
"active": true,
"tax_exempt": false,
"pay_what_you_want": false,
"inventory_managed": false,
"sold_out": false
},
"has": {
"digital_delivery": false,
"physical_delivery": false,
"images": true
},
"collects": {
"fullname": false,
"shipping_address": false,
"billing_address": false,
"extra_fields": false
},
"checkout_url": {
"checkout": "https://checkout.chec.io/tE45fb?checkout=true",
"display": "https://checkout.chec.io/tE45fb"
},
"extra_fields": [],
"variant_groups": [],
"categories": [],
"assets": [
{
"id": "ast_8XO3wpM74OoYAz",
"url": "https://cdn.chec.io/merchants/37076/assets/1WUVJv226CmE5Xp2|air-jordan-11-cool-grey-ct8012-005-release-date (1).jpg",
"description": null,
"is_image": true,
"filename": "air-jordan-11-cool-grey-ct8012-005-release-date (1).jpg",
"file_size": 24857,
"file_extension": "jpg",
"image_dimensions": {
"width": 960,
"height": 1080
},
"meta": [],
"created_at": 1639554944,
"updated_at": 1639554948
},
{
"id": "ast_bO6J5aBxDElEjp",
"url": "https://cdn.chec.io/merchants/37076/assets/xRQc9seG948wu332|download (1).jfif",
"description": null,
"is_image": true,
"filename": "download (1).jfif",
"file_size": 7152,
"file_extension": "jpg",
"image_dimensions": {
"width": 294,
"height": 171
},
"meta": [],
"created_at": 1639554948,
"updated_at": 1639554949
},
{
"id": "ast_A12JwrMQExlPjn",
"url": "https://cdn.chec.io/merchants/37076/assets/5RmVeAD6AX6l1O7D|download.jfif",
"description": null,
"is_image": true,
"filename": "download.jfif",
"file_size": 5551,
"file_extension": "jpg",
"image_dimensions": {
"width": 266,
"height": 190
},
"meta": [],
"created_at": 1639554959,
"updated_at": 1639554961
}
],
"image": {
"id": "ast_8XO3wpM74OoYAz",
"url": "https://cdn.chec.io/merchants/37076/assets/1WUVJv226CmE5Xp2|air-jordan-11-cool-grey-ct8012-005-release-date (1).jpg",
"description": null,
"is_image": true,
"filename": "air-jordan-11-cool-grey-ct8012-005-release-date (1).jpg",
"file_size": 24857,
"file_extension": "jpg",
"image_dimensions": {
"width": 960,
"height": 1080
},
"meta": [],
"created_at": 1639554944,
"updated_at": 1639554948
},
"related_products": [],
"attributes": []
},
{
"id": "prod_BkyN5YVzyxl0b6",
"created": 1639564691,
"updated": 1639564756,
"active": true,
"permalink": "BPMQ0E",
"name": "Air Jordan 5 Green Bean",
"description": "",
"price": {
"raw": 400000,
"formatted": "400,000.00",
"formatted_with_symbol": "Rp400,000.00",
"formatted_with_code": "400,000.00 IDR"
},
"inventory": {
"managed": false,
"available": 0
},
"sku": null,
"sort_order": 0,
"seo": {
"title": null,
"description": null
},
"thank_you_url": null,
"meta": null,
"conditionals": {
"is_active": true,
"is_tax_exempt": false,
"is_pay_what_you_want": false,
"is_inventory_managed": false,
"is_sold_out": false,
"has_digital_delivery": false,
"has_physical_delivery": false,
"has_images": true,
"collects_fullname": false,
"collects_shipping_address": false,
"collects_billing_address": false,
"collects_extra_fields": false
},
"is": {
"active": true,
"tax_exempt": false,
"pay_what_you_want": false,
"inventory_managed": false,
"sold_out": false
},
"has": {
"digital_delivery": false,
"physical_delivery": false,
"images": true
},
"collects": {
"fullname": false,
"shipping_address": false,
"billing_address": false,
"extra_fields": false
},
"checkout_url": {
"checkout": "https://checkout.chec.io/BPMQ0E?checkout=true",
"display": "https://checkout.chec.io/BPMQ0E"
},
"extra_fields": [],
"variant_groups": [],
"categories": [
{
"id": "cat_O3bR5XyEklnzdj",
"slug": "new-releases",
"name": "New Releases"
}
],
"assets": [
{
"id": "ast_8XO3wpM7yOoYAz",
"url": "https://cdn.chec.io/merchants/37076/assets/L4NaqCsUMMxS6Ie8|2022-Air-Jordan-5-Green-Bean-1068x707.jpg",
"description": null,
"is_image": true,
"filename": "2022-Air-Jordan-5-Green-Bean-1068x707.jpg",
"file_size": 60899,
"file_extension": "jpg",
"image_dimensions": {
"width": 1068,
"height": 707
},
"meta": [],
"created_at": 1639564675,
"updated_at": 1639564678
}
],
"image": {
"id": "ast_8XO3wpM7yOoYAz",
"url": "https://cdn.chec.io/merchants/37076/assets/L4NaqCsUMMxS6Ie8|2022-Air-Jordan-5-Green-Bean-1068x707.jpg",
"description": null,
"is_image": true,
"filename": "2022-Air-Jordan-5-Green-Bean-1068x707.jpg",
"file_size": 60899,
"file_extension": "jpg",
"image_dimensions": {
"width": 1068,
"height": 707
},
"meta": [],
"created_at": 1639564675,
"updated_at": 1639564678
},
"related_products": [],
"attributes": []
}
]
is there a way to efficiently and cleanly find products based on their categories? Thank you in advance.
Yes. There is a way by using the category 'slug'.
import Commerce from '#chec/commerce.js';
const commerce = new Commerce('{your_public_key}');
// Fetch products specifying a category slug
commerce.products.list({
category_slug: ['shoes'],
}).then(response => response.data);
// Fetch products specifying multiple category slugs
commerce.products.list({
category_slug: ['shoes', 'black'],
}).then(response => response.data);
For more details:
https://commercejs.com/docs/sdk/products#retrieve-product
i have a json returned from an api that shows latest discussions from a forum..
the url that display the json output is like:
https://example.com/api/discussions?isApproved=true&exists=true&sort=-lastPostedAt
and this is the json output:
"links": {
"first": "http://localhost/flarum/public/api/discussions?isApproved=true\u0026exists=true\u0026sort=-lastPostedAt",
"next": "http://localhost/flarum/public/api/discussions?isApproved=true\u0026exists=true\u0026sort=-lastPostedAt\u0026page%5Boffset%5D=20"
},
"data": [
{
"type": "discussions",
"id": "46",
"attributes": {
"title": "footer",
"slug": "46-footer",
"commentCount": 1,
"participantCount": 1,
"createdAt": "2021-09-20T07:14:18+00:00",
"lastPostedAt": "2021-09-20T07:14:18+00:00",
"lastPostNumber": 1,
"canReply": true,
"canRename": true,
"canDelete": true,
"canHide": true,
"lastReadAt": "2021-09-20T07:14:20+00:00",
"lastReadPostNumber": 1,
"isApproved": true,
"canTag": true,
"subscription": null,
"isLocked": false,
"canLock": true
},
"relationships": { "user": { "data": { "type": "users", "id": "1" } }, "lastPostedUser": { "data": { "type": "users", "id": "1" } }, "tags": { "data": [{ "type": "tags", "id": "2" }] } }
},
{
"type": "discussions",
"id": "45",
"attributes": {
"title": "fhgfhfg",
"slug": "45-fhgfhfg",
"commentCount": 2,
"participantCount": 1,
"createdAt": "2021-09-19T16:07:37+00:00",
"lastPostedAt": "2021-09-19T23:04:00+00:00",
"lastPostNumber": 2,
"canReply": true,
"canRename": true,
"canDelete": true,
"canHide": true,
"lastReadAt": "2021-09-19T23:04:02+00:00",
"lastReadPostNumber": 2,
"isApproved": true,
"canTag": true,
"subscription": null,
"isLocked": false,
"canLock": true
},
"relationships": { "user": { "data": { "type": "users", "id": "1" } }, "lastPostedUser": { "data": { "type": "users", "id": "1" } }, "tags": { "data": [{ "type": "tags", "id": "2" }] } }
},
{
"type": "discussions",
"id": "39",
"attributes": {
"title": "Discussion",
"slug": "39-discussion",
"commentCount": 21,
"participantCount": 1,
"createdAt": "2021-05-22T11:06:43+00:00",
"lastPostedAt": "2021-09-04T12:49:32+00:00",
"lastPostNumber": 28,
"canReply": true,
"canRename": true,
"canDelete": true,
"canHide": true,
"lastReadAt": "2021-09-04T12:49:34+00:00",
"lastReadPostNumber": 28,
"isApproved": true,
"canTag": true,
"subscription": null,
"isLocked": false,
"canLock": true
},
"relationships": { "user": { "data": { "type": "users", "id": "1" } }, "lastPostedUser": { "data": { "type": "users", "id": "1" } }, "tags": { "data": [{ "type": "tags", "id": "1" }] } }
}
what i want to do is to have something like "related content" based on a discussion title. For example if i have this title "lets talk about cars", the json must shows all the discussions related to this title.
is this possible?
You can take the data from json and just filter the content inside
const filteredResults = yourJsonResponse.data.filter(item => item.attributes.title === 'lets talk about cars')
This won't be a good idea. as you're getting paginated list with limit(like per page 20/30). if you're using js you can use js filter for getting related content. But as i said. that filer will be done based on your current page data, not all data. it's better to use another api end for related content from large data..
I'm manipulating some javascript objects and I want to know if is there a more efficient and easy way to process my data.
I already do that, but I'm a beginner in js.
I have four objects with this structure: basically there is an array of blocks and any object has a different number of blocks. In every block, in the features attribute, I have another array with some features.
Then I have another object, and I have to remove from this object (I call it structure) blocks and features that are not present in my four initial object.
This is a sample product object
[
{
"ID": 16293,
"SortNo": "20",
"FeatureGroup": {
"ID": "148",
"Name": {
"Value": "Design",
"Language": "IT"
}
},
"Features": [
{
"Localized": 0,
"ID": "155744521",
"Type": "dropdown",
"Value": "Round",
"CategoryFeatureId": "85327",
"CategoryFeatureGroupID": "16293",
"SortNo": "155",
"PresentationValue": "Rotondo",
"RawValue": "Round",
"LocalValue": [],
"Description": "The external form",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "9397",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Forma",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155655523",
"Type": "multi_dropdown",
"Value": "White",
"CategoryFeatureId": "85298",
"CategoryFeatureGroupID": "16293",
"SortNo": "90",
"PresentationValue": "Bianco",
"RawValue": "White",
"LocalValue": [],
"Description": "The colour of the housing",
"Mandatory": "1",
"Searchable": "1",
"Feature": {
"ID": "10059",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Colore struttura",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155655525",
"Type": "multi_dropdown",
"Value": "White",
"CategoryFeatureId": "85301",
"CategoryFeatureGroupID": "16293",
"SortNo": "80",
"PresentationValue": "Bianco",
"RawValue": "White",
"LocalValue": [],
"Description": "The colour of the band",
"Mandatory": "1",
"Searchable": "1",
"Feature": {
"ID": "11025",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Colore cinturino",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "219617494",
"Type": "y_n",
"Value": "Y",
"CategoryFeatureId": "168947",
"CategoryFeatureGroupID": "16293",
"SortNo": "-6",
"PresentationValue": "Sì",
"RawValue": "Y",
"LocalValue": [],
"Description": "The product is protected from water",
"Mandatory": "0",
"Searchable": "0",
"Feature": {
"ID": "7509",
"Sign": "",
"Measure": {
"ID": "26",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Resistente all'acqua",
"Language": "IT"
}
}
}
]
},
{
"ID": 34567,
"SortNo": "20",
"FeatureGroup": {
"ID": "184",
"Name": {
"Value": "Prestazione",
"Language": "IT"
}
},
"Features": [
{
"Localized": 0,
"ID": "155744528",
"Type": "y_n",
"Value": "N",
"CategoryFeatureId": "94697",
"CategoryFeatureGroupID": "34567",
"SortNo": "800",
"PresentationValue": "No",
"RawValue": "N",
"LocalValue": [],
"Description": "La Frequenza modulare radio produce la miglior recezione di qualsiasi canale radio. Quando viene usato un auricolare, produce un effetto di suono da stereo r",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "2172",
"Sign": "",
"Measure": {
"ID": "26",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Radio FM",
"Language": "IT"
}
}
},
{
"Localized": 0,
"ID": "155744530",
"Type": "multi_dropdown",
"Value": "Not supported",
"CategoryFeatureId": "85357",
"CategoryFeatureGroupID": "34567",
"SortNo": "500",
"PresentationValue": "Non supportato",
"RawValue": "Not supported",
"LocalValue": [],
"Description": "Types of memory cards which can be used with this product.",
"Mandatory": "1",
"Searchable": "0",
"Feature": {
"ID": "730",
"Sign": "",
"Measure": {
"ID": "29",
"Sign": "",
"Signs": {
"ID": "",
"_": "",
"Language": "IT"
}
},
"Name": {
"Value": "Tipi schede di memoria",
"Language": "IT"
}
}
}
]
}
]
Here i loop my initial objects (this.compare_products) to extract, in two arrays (featureGroupIds - featureIds) the ID of my block and the CategoryFeatureId
let featureGroupIds = []
let featureIds = []
this.compare_products.forEach((object) => {
featureGroupIds = featureGroupIds.concat(FeaturesGroups.map(o => o.ID))
featureIds = featureIds.concat(FeaturesGroups.map(o => o.Features.map(o => o. CategoryFeatureId))).flat(2)
})
The two arrays, featureGroupIds and featureIds are now filled with every block ID and every CategoryFeatureId present in my four object.
Now I have to filter the object I call "structure" to remove the block and the features with an ID that is not present in my arrays.
This is my structure, and as you can see is similar.
[
{
"name": "Display",
"data": {
"id": 34566,
"category_id": 2647
},
"features": [
{
"name": "Tipo di display",
"data": {
"id": 85325,
"category_id": 2647,
"feature_id": 9104,
"category_feature_group_id": 34566,
"order": 10100140
}
},
{
"name": "Touch screen",
"data": {
"id": 85331,
"category_id": 2647,
"feature_id": 4963,
"category_feature_group_id": 34566,
"order": 10100129
}
},
{
"name": "Dimensioni schermo",
"data": {
"id": 158002,
"category_id": 2647,
"feature_id": 3544,
"category_feature_group_id": 34566,
"order": 100149
}
},
{
"name": "à di Pixel",
"data": {
"id": 85347,
"category_id": 2647,
"feature_id": 13246,
"category_feature_group_id": 34566,
"order": 100147
}
},
{
"name": "Tipo di vetro",
"data": {
"id": 94704,
"category_id": 2647,
"feature_id": 7610,
"category_feature_group_id": 34566,
"order": 100050
}
}
]
},
{
"name": "Altre caratteristiche",
"data": {
"id": 34569,
"category_id": 2647,
"feature_group_id": 146,
"name": null,
"order": 0
},
"features": [
{
"name": "inside",
"data": {
"id": 110410,
"category_id": 2647,
"feature_id": 18688,
"category_feature_group_id": 34569,
"order": 100000
}
}
]
}
]
Here is my function
structure = structure.filter(featureGroup => this.featureGroupIds.includes(featureGroup.data.id));
structure.map((object) => {
object.features.filter(feature => this.featureIds.includes(feature.data.feature_id))
})
this.featureIds and this.featureGroupIds are the array with the group IDS and with the feature IDS.
Is there a more efficient way to do this?
I have 2 nested array and I want to check if id's from the list1 and if there are same id in the list2 add that object of the list2 + tag and count from the list1 to a new array.New array has the tag,count and the list of details of id that is in the list1 and is same as id in the list2
Note: these 2 lists doesn't have the same size
Thank in advance for help
For example:
list1
const list1 = [
{
"id": [
"5cca1dbc-dd5c-498f-8f83-735062c05240",
"2a10c30a-7c3a-4081-8246-9d37e19c2d6f",
"3128f36c-1c79-4301-b08f-e0182c256c03"
],
"tag": "tag1",
"count": {
"low": 53,
"high": 0
}
},
{
"id": [
"510019af-1728-4628-9019-343cd3c1b3e1",
"fb420746-4d11-4d2e-ab7f-b8a73e5b8f8e",
"adf0cd4c-3072-4ecf-9aa7-ecd5580c31ae"
],
"tag": "tag2",
"count": {
"low": 43,
"high": 0
}
}
]
list2
[
{
"id": "5cca1dbc-dd5c-498f-8f83-735062c05240",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [
{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}
],
"topics": [
{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
},
{
"id": "fb420746-4d11-4d2e-ab7f-b8a73e5b8f8e",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [
{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}
],
"topics": [
{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
},
{
"id": "efde2bc9-018b-49c1-9c01-a4eda9817a33",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [
{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}
],
"topics": [
{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
}
]
new array
[
{
"tag": "tag1",
"count": {
"low": 53,
"high": 0
},
"details": [
{
"id": "5cca1dbc-dd5c-498f-8f83-735062c05240",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [
{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}
],
"topics": [
{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
}
]
}
]
Iterate through list1, check if the id exists in list2 and if it does add it to a new array.
e.g.
var result = [];
for (let item of list1) {
let details = list2.filter(l2 => item.id.includes(l2.id));
if (details.length > 0) {
result.push({
tag: item.tag,
count: item.count,
details: details
});
}
}
If you want all items in list1 to show up regardless of the id existing in list2 you could use map and return a new object for each item in list1.
var result = list1.map(l1 => {
return {
tag: l1.tag,
count: l1.count,
details: list2.filter(l2 => l1.id.includes(l2.id))
};
});
const list1 = [{
"id": [
"5cca1dbc-dd5c-498f-8f83-735062c05240",
"2a10c30a-7c3a-4081-8246-9d37e19c2d6f",
"3128f36c-1c79-4301-b08f-e0182c256c03"
],
"tag": "tag1",
"count": {
"low": 53,
"high": 0
}
},
{
"id": [
"510019af-1728-4628-9019-343cd3c1b3e1",
"fb420746-4d11-4d2e-ab7f-b8a73e5b8f8e",
"adf0cd4c-3072-4ecf-9aa7-ecd5580c31ae"
],
"tag": "tag2",
"count": {
"low": 43,
"high": 0
}
}
];
const list2 = [{
"id": "5cca1dbc-dd5c-498f-8f83-735062c05240",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}],
"topics": [{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
},
{
"id": "fb420746-4d11-4d2e-ab7f-b8a73e5b8f8e",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}],
"topics": [{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
},
{
"id": "efde2bc9-018b-49c1-9c01-a4eda9817a33",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}],
"topics": [{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
}
];
var result1 = [];
for (let item of list1) {
let details = list2.filter(l2 => item.id.includes(l2.id));
if (details.length > 0) {
result1.push({
tag: item.tag,
count: item.count,
details: details
});
}
}
console.log(result1);
var result2 = list1.map(l1 => {
return {
tag: l1.tag,
count: l1.count,
details: list2.filter(l2 => l1.id.includes(l2.id))
};
});
console.log(result2);
You can use array.forEach,
First you need to take list1 and loop through each item, inside each item you have property called id, which is again a collection of array. you need to do a foreach with the id and check with the list2 and once the list2.id matches with the id of list 1 . it should push an object of your required output.
I hope the below code will solve the issue.
const list1 = [
{
"id": [
"5cca1dbc-dd5c-498f-8f83-735062c05240",
"2a10c30a-7c3a-4081-8246-9d37e19c2d6f",
"3128f36c-1c79-4301-b08f-e0182c256c03"
],
"tag": "tag1",
"count": {
"low": 53,
"high": 0
}
},
{
"id": [
"510019af-1728-4628-9019-343cd3c1b3e1",
"fb420746-4d11-4d2e-ab7f-b8a73e5b8f8e",
"adf0cd4c-3072-4ecf-9aa7-ecd5580c31ae"
],
"tag": "tag2",
"count": {
"low": 43,
"high": 0
}
}
]
const list2 = [
{
"id": "5cca1dbc-dd5c-498f-8f83-735062c05240",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [
{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}
],
"topics": [
{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
},
{
"id": "fb420746-4d11-4d2e-ab7f-b8a73e5b8f8e",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [
{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}
],
"topics": [
{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
},
{
"id": "efde2bc9-018b-49c1-9c01-a4eda9817a33",
"createdDate": "2017-10-08T22:40:33.020Z",
"modifiedDate": "2017-10-08T22:40:33.020Z",
"title": "Good morning! #tag1",
"text": " ",
"media": [
{
"id": "1f8c564c-91f1-457c-b4c1-0820c03861b4",
"metadata": {
"mimetype": "image/jpeg",
"imageHeight": 400,
"imageWidth": 300
}
}
],
"topics": [
{
"topicId": "22a96a83-def3-4981-bc91-9277464b7105"
},
{
"name": "Fashion",
"topicId": "6d4caea2-8387-42f3-977d-06a4bb063c44"
}
],
"language": null,
"sourceId": "d25205ca-2ef308261113",
}
]
var arr = []
list1.forEach(l1I => {
l1I.id.forEach(eID => list2.forEach(l2I => {
if(l2I.id === eID){
var obj = {}
obj["details"] = l2I;
obj["tag"] = l1I.tag;
obj["count"] = l1I.count;
arr.push(obj);
}
}))
})
console.log("output", arr)
Thank you so much for your responses,
I could solve it that day by this:
const responseValueList = {};
const hashtagsList = [];
for (const responseRow of list1) {
const obj = {};
obj.hashtagName = responseRow.hashtag;
obj.hashtagCount = responseRow.count;
const rateableList = []
for (const responseSectionTwo of list2) {
if (responseRow.id.includes(responseSectionTwo.id)) {
rateableList.push(responseSectionTwo);
}
}
obj.hashtagItems = rateableList;
hashtagsList.push(obj);
}
Thanks again