how to read another javascript JSON categories - javascript

I have no idea how to make this,
I have a loop for product List Item, but i really don't know how to link the shop item to shop name. I have tried many method but i really don't know how to link the item to the shop.
if productList.ShopId = shopList.id then use this shopList.title
SHOP NAME = shopList.title
const getProductList = function (productItem) {
const productListRender =
$('<div>').append($('<span>', {
html: shopName() <<<< SHOP NAME
}));
$.each(data.shopList), function shopName() {
this.text(shopList.title);
};
return productListRender;
}
const $product = $('#List')
$.each(data.productList, function (index, data) {
$product.append(getProductList(data));
});
Data JS is Below:
var data = {
productList: [
{
id: "62276197-6059-4c21-9b40-c5b1d277e85d",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000001_12032019.png",
text: 'Product 001',
goldMedal: false,
newItem: true,
newShop: true,
freeDelivery: true,
ShopId: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb'
},
{
id: "59de8216-052d-4e51-9f7d-7e96642ded62",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000002_12032019.png",
text: 'Product 002',
goldMedal: true,
newItem: false,
newShop: true,
freeDelivery: true,
ShopId: '10eb4250-47d6-41ad-a429-f65e05836f26'
},
{
id: "59de8216-052d-4e51-9f7d-7e96642ded62",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000003_12032019.png",
text: 'Product 003',
goldMedal: true,
newItem: false,
newShop: true,
freeDelivery: true,
ShopId: '10eb4250-47d6-41ad-a429-f65e05836f26'
}],
shopList: [{
id: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb',
title: 'Shop 001'
},
{
id: '10eb4250-47d6-41ad-a429-f65e05836f26',
title: 'Test Shop'
}]
}

Refine shopName as:
function shopName(shopId) {
// find the right shop by comparing shopId with each `shop.id`
// uses optional chaining to prevent errors
// returns undefineds if no match is found
return shopList.filter(shop => shop.id === shopId)?.[0]?.title;
}
const shopList = [{
id: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb',
title: 'Shop 001'
},
{
id: '10eb4250-47d6-41ad-a429-f65e05836f26',
title: 'Test Shop'
}]
console.log(shopName('10eb4250-47d6-41ad-a429-f65e05836f26'));
console.log(shopName('222'));

everything seems to be in order in your data. only thing that i can see is that there was some mishap in your comparison method.
have you tried comparing them not with equal sign but rather treat them as string .
you could see this link for reference..
https://www.tutorialspoint.com/What-is-the-best-way-to-compare-two-strings-in-JavaScript

Related

How to update sub array item in MongoDB, JavaScript

So let's say I have this piece of code:
const old = await Sports.findById(sportId);
And it returns the following:
{
_id: "sdsdsds",
name: "sdsdsds",
enabled: true,
markets: [
{
enabled: true,
defId: "LOOKATME",
name: "sdsdsd",
},
{
enabled: false,
defId: "dfsdfdsfs",
name: "sdsdfsdsd",
},
]
}
Now, let's say I want to update the market with the defId of "LOOKATME" so it enabled becomes false.
Would it be possible to added inside an update function such as this:
const updated = await Sports.findByIdAndUpdate(old, [LOGIC], {new: true});
How would I go about doing this so the output is this:
{
_id: "sdsdsds",
name: "sdsdsds",
enabled: true,
markets: [
{
enabled: false, // this is what changed
defId: "LOOKATME",
name: "sdsdsd",
},
{
enabled: false,
defId: "dfsdfdsfs",
name: "sdsdfsdsd",
},
]
}
const updated = await Sports.updateOne({_id: old._id, "markets.defId": "LOOKATME"}, {$set: {"markets.$.enabled": false}}, {new: true});

show product base on browser url

I want to show product dynamic base on browser link. For example if
http://www.example.com?product=[data.productList.id] then show data.productList.text
Expected results: if http://www.example.com?product=62276197-6059-4c21-9b40-c5b1d277e85d then show Product 001.
I have tried many method.
My js is below :
const browserId = data.productList.id
if (window.location.href.contains('?product=' + browserId) > -1) {
$('.test').append(productItemName(data.productList.id))
}
function productItemName(productName) {
return data.productList.filter(product => product.id === productName)?.[0]?.id;
}
my data js is below:
var data = {
productList: [
{
id: "62276197-6059-4c21-9b40-c5b1d277e85d",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000001_12032019.png",
text: 'Product 001',
price: '368.00',
hitRate: '45472',
goldMedal: false,
newItem: true,
newShop: true,
freeDelivery: true,
ShopId: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb'
},
{
id: "4a074028-d72a-4954-a159-f41adeb5cc5b",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000002_12032019.png",
text: 'Product 002',
price: '99.00',
hitRate: '25241',
goldMedal: true,
newItem: false,
newShop: true,
freeDelivery: true,
ShopId: '10eb4250-47d6-41ad-a429-f65e05836f26'
}]
}
html is below:
<div class="test"></div>
You can get value which is under product using searchParams.get("product"); and then pass same to your function to get required text.
Demo Code :
//your json data
var data = {
productList: [{
id: "62276197-6059-4c21-9b40-c5b1d277e85d",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000001_12032019.png",
text: 'Product 001',
price: '368.00',
hitRate: '45472',
goldMedal: false,
newItem: true,
newShop: true,
freeDelivery: true,
ShopId: '5cfb048c-86e8-4d2d-85bf-e4e9e1effdcb'
},
{
id: "4a074028-d72a-4954-a159-f41adeb5cc5b",
link: "javascript:void(0)",
imgurl: "/img/upload/png/joyacart_000002_12032019.png",
text: 'Product 002',
price: '99.00',
hitRate: '25241',
goldMedal: true,
newItem: false,
newShop: true,
freeDelivery: true,
ShopId: '10eb4250-47d6-41ad-a429-f65e05836f26'
}
]
}
//your url
var url_string = "http://www.example.com?product=62276197-6059-4c21-9b40-c5b1d277e85d";
var url = new URL(url_string);
//get product parameter value
var browserId = url.searchParams.get("product");
//checking if id is not null
if (browserId != null) {
//pass id
$('.test').append(productItemName(browserId))
}
function productItemName(productName) {
return data.productList.filter(product => product.id === productName)?.[0]?.text;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"></div>
at my webconsole productItemName function errors me with bad syntax (meaning this ?.[0]?.text)
try this
function productItemName(productName) {
let result = data.productList.find((item) => item.id === productName);
return result !== undefined ? result.text : "Not Found";
}

Looking for a more concise approach to manipulate an array with nested data

I'm currently working on an Angular application and want to iterate over an array of objects that have nested data. I want to mutate the existing array when a user clicks a checkbox changing the checked property from false to true and vise Versa. For simplicity sake, I'm only posting the array structure.
I tried
const checklistCashe = [
{
categories: [
{
title: "Administrators",
items: [
{subTitle: "Admin", checked: false},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
]
},
{
title: "Associates",
items: [
{subTitle: "Admin", checked: false},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
{subTitle: "Users", checked: false},
]
},
{
title: "Organization",
items: [
{subTitle: "Contract", checked: false},
{subTitle: "External", checked: false},
{subTitle: "Internal", checked: false},
]
},
{
title: "Products",
items: [
{subTitle: "Concept", checked: false},
{subTitle: "Demo", checked: false},
{subTitle: "Production", checked: false},
]
},
{
title: "Reporting",
items: [
{subTitle: "Admin", checked: false},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
]
}
]
}
]
const category = "Reporting";
const subCategory = "Admin";
I want to mutate the current array based on the category and subCategory provided. So I only want the checked property to change if the title is Reporting and the subTitle is Admin.
{
title: "Reporting",
items: [
{subTitle: "Admin", checked: true},
{subTitle: "Associates", checked: false},
{subTitle: "Hr", checked: false},
]
}
The best way with what you have would be something like:
function toggleChecked(title, subtitle) {
checklistCashe[0].categories.forEach((category) => {
if (category.title === title) {
category.items.forEach((item) => {
if (item.subTitle === subtitle) {
item.checked = !item.checked;
}
});
}
});
}
However, I feel like you might be better off formatting your checklistCashe to something more like:
const checklistCashe = {
Administrators: {
Admin: false,
Associates: false,
Hr: false
}
[...]
}
Then you can do something more like:
function toggleChecked(title, subtitle) {
checklistCashe[title][subtitle] = !checklistCashe[title][subtitle]
}
and you wouldn't have to iterate.
If you wanna keep it clean then use lodash as shown below
const checkListCache = [
{
categories: [
{
title: 'Administrators',
items: [
{ subTitle: 'Admin', checked: false },
{ subTitle: 'Associates', checked: false },
{ subTitle: 'Hr', checked: false },
],
},
{
title: 'Associates',
items: [
{ subTitle: 'Admin', checked: false },
{ subTitle: 'Associates', checked: false },
{ subTitle: 'Hr', checked: false },
{ subTitle: 'Users', checked: false },
],
},
{
title: 'Organization',
items: [
{ subTitle: 'Contract', checked: false },
{ subTitle: 'External', checked: false },
{ subTitle: 'Internal', checked: false },
],
},
{
title: 'Products',
items: [
{ subTitle: 'Concept', checked: false },
{ subTitle: 'Demo', checked: false },
{ subTitle: 'Production', checked: false },
],
},
{
title: 'Reporting',
items: [
{ subTitle: 'Admin', checked: false },
{ subTitle: 'Associates', checked: false },
{ subTitle: 'Hr', checked: false },
],
},
],
},
];
const category = 'Reporting';
const subCategory = 'Admin';
const { categories } = checkListCache[0];
const selectedCategory = _.find(categories, ['title', category]);
const selectedSubCategory = _.find(selectedCategory.items, ['subTitle', subCategory]);
selectedSubCategory.checked = !selectedSubCategory.checked;
console.log(checkListCache);
You can add safety checks as well before each loop to ensure we have values before manipulating it.
Use nested map calls:
function mutate (arr)
{
return arr.map(innerArr =>
{
return {
title: innerArr.title,
items: innerArr.items.map(item => {
return {
subTitle: item.subTitle,
checked: (innerArr.title === "Reporting" && item.subTitle === "Admin") ? false : item.checked,
};
}),
};
});
}

Check if value is in array and return true or false angular 6+

I have some array like this
roles = ['AnyRulesGo#admin', 'NoRules#admin', 'HowYesNo#history', 'MamaMia#survey'];
And i have some object like this
externalLinks = [
{
link: '#',
icon: 'Icon',
translation: 'Home',
role: '#history',
active: false,
visible: false
},
{
link: '#',
icon: 'Task',
translation: 'Tasks',
role: '#task',
active: false,
visible: false
},
{
link: '#',
icon: 'Files',
translation: 'Files',
role: '#admin',
active: true,
visible: false
}
];
I need some function to check does value role in externaLinks exists in array roles, and update that value visible in externalLinks from false to true
I dont have much more code, because i dont know even where to start from, any help will be great, thanks
One of the problem is that i done have netire role name only started from # it means I need to cut that string, and than compare?
I have tried with this function, but no luck
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
You can iterate through each object in externalLinks using array#forEach. Then check for role in the roles array using array#some and string#incldues and update the value of visible key.
let roles = ['AnyRulesGo#admin', 'NoRules#admin', 'HowYesNo#history', 'MamaMia#survey'],
externalLinks = [ { link: '#', icon: 'Icon', translation: 'Home', role: '#history', active: false, visible: false }, { link: '#', icon: 'Task', translation: 'Tasks', role: '#task', active: false, visible: false }, { link: '#', icon: 'Files', translation: 'Files', role: '#admin', active: true, visible: false } ];
externalLinks.forEach(o => {
o.visible = false;
if(roles.some(r => r.includes(o.role)))
o.visible = true;
});
console.log(externalLinks);
You can use forEach to loop over external links. Then use some and includes to check if role exist.
roles = ['AnyRulesGo#admin', 'NoRules#admin', 'HowYesNo#history', 'MamaMia#survey'];
externalLinks.forEach((extLink) => {
if(roles.some(role => role.includes(extLink.role))){
extLink.visible = true;
}
})
make two loop:
//Make all false
externalLinks.forEach(x=>x.visible=false);
//for each role, filter by role and forEach value filtered, make visible
role.forEach(role=>{
let busc="#"+role.split('#')[1]
externalLinks.filter(x=>x.role==busc)
.forEach(xfilter=>xfilter.visible=true)
})
//If only want a role "roleSearch"
let busc="#"+roleSearch.split('#')[1]
externalLinks.filter(x=>x.role==busc)
.forEach(xfilter=>xfilter.visible=true)

Grouping values in grid panel after double clicking

I want to group the values in grid panel
Below is the code:
var store = Ext.create('Ext.data.TreeStore', {
root: {
expanded: true,
children: [
{ text: "School Friends", expanded: true, children: [
{ text: "Mike", leaf: true, name: "Mike", email: "mike#stackoverflow.com", phone: "345-2222"},
{ text: "Laura", leaf: true, name: "Laura", email: "laura#stackoverflow.com", phone: "345-3333"}
] },
{ text: "Facebook Friend", expanded: true, children: [
{ text: "Steve", leaf: true, name: "Steve", email: "steve#stackoverflow.com", phone: "345-2222"},
{ text: "Lisa", leaf: true, name: "Lisa", email: "lisa#stackoverflow.com", phone: "345-3333"}
] },
]
}});
Ext.create('Ext.tree.Panel', {
title: 'All My Friends',
width: 200,
height: 150,
store: store,
rootVisible: false,
renderTo: Ext.getBody(),
listeners : {
itemdblclick : function(tree, record, index){
Ext.getStore('simpsonsStore').loadRawData([record.raw], true);
}
}});
Ext.create('Ext.data.Store', {
storeId:'simpsonsStore',
fields:['name', 'email', 'phone'],
data:{'items':[
{ 'name': 'Bart', "email":"bart#simpsons.com", "phone":"555-222-1234" },
{ 'name': 'Homer', "email":"home#simpsons.com", "phone":"555-222-1244" },
{ 'name': 'Marge', "email":"marge#simpsons.com", "phone":"555-222-1254" }
]},
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'items'
}
}});
Ext.create('Ext.grid.Panel', {
title: 'Best Friends',
store: Ext.data.StoreManager.lookup('simpsonsStore'),
columns: [
{ text: 'Name', dataIndex: 'name' },
{ text: 'Email', dataIndex: 'email', flex: 1 },
{ text: 'Phone', dataIndex: 'phone' }
],
height: 200,
width: 400,
renderTo: Ext.getBody()});
From the above code I am able to get the values from treepanel to grid panel by double clicking.
I want an extra column to group values if we double click the same leaf in the treepanel.
For example if we double click Bart 6 times
Name email phonenumber groupby(number of times)
Bart bart#simpsons.com 555-222-1234 6
It should not append same value in the grid panel.
Could any one please help me.
Regards,
sreekanth
You'll need to add a count field to your store's fields. Then, you'll need to add the field to your grid. When you double-click the tree, you'll need to check the store to see if the record already exists. If it does, change the value in the count field; otherwise, add a new row.
itemdblclick: function (tree, record, index) {
var s = Ext.getStore('simpsonsStore'),
existingRecIdx = s.findBy(function (r) {
return r.get('email') === record.raw['email'];
});
if (existingRecIdx === -1) { //row not found
record.raw.clickCt = 1;
s.loadRawData([record.raw], true);
} else {
var r = s.getAt(existingRecIdx);
r.data.clickCt++;
grid.getView().refresh(); //once the data has changed
//refresh the grid
}
}
See http://jsfiddle.net/Kk7gL/

Categories

Resources