Please help me rewrite or add right condition to the Vue js code
Basically, I need to make sure variable shops is empty, only, if all the account va开发者_Python百科lues are empty in the map function below.
if (coll.cellData.name === 'account') {
individualData = {
isSearch: true,
account_name: object.name,
shops: connectedShops.map(shop => ({
shop_name: shop.name,
shop_id: shop.id,
currency_code: shop.currency.name,
account: object.accounts.find(acc => acc.shop_id === shop.id) ? ? null,
})),
};
}
Do not have much practise in JS and do not know how to add a condition. Thank you!
I have this code to run after, but sure you can suggest a better idea
var custom_mapping = true;
for (shop in connectedShops) {
if (object.accounts.find(acc => acc.shop_id === shop.id) === null)
custom_mapping = false;
}
if (!custom_mapping)
individualData.shop = []
try this.
if (coll.cellData.name === 'account') {
individualData = {
isSearch: true,
account_name: object.name,
shops: connectedShops.flatmap(shop => {
if(!object.accounts.find(acc => acc.shop_id === shop.id)) return [];
else return {
shop_name: shop.name,
shop_id: shop.id,
currency_code: shop.currency.name,
account: object.accounts.find(acc => acc.shop_id === shop.id)
}
}),
};
}
if object.accounts.find(acc => acc.shop_id === shop.id)
return undefined
meaning it can't find shop_id
in object.accounts
, then we return empty array.
You can achieve this requirement by test if all the account
values are empty or not with the help of Array.some()
method.
Live Demo :
const obj = {
accounts: [{
shop_id: 1
}, {
shop_id: 2
}, {
shop_id: 4
}, {
shop_id: 5
}]
};
const connectedShops = [{
name: 'Shop A',
id: 1,
currency: {
name: 'INR'
}
}, {
name: 'Shop B',
id: 3,
currency: {
name: 'USD'
}
}];
const shops = connectedShops.map(shop => {
return obj.accounts.some(({ shop_id }) => shop_id === shop.id) ? {
account: obj.accounts.find(({shop_id}) => shop_id === shop.id)
} : []
});
console.log(shops);
精彩评论