Related
I tried to filter a message in Discord.js based on its author and the message type.
Here's the raw data:
[
[
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256144094175392",
"createdTimestamp": 1662126327299,
"type": 0,
"system": false,
"content": "https://youtube.com",
"authorId": "530963824396992514",
"pinned": false,
"tts": false,
"nonce": "1015256103077806080",
"embeds": [
{
"type": "link",
"url": "https://youtube.com/",
"title": "YouTube",
"description": "Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.",
"thumbnail": {
"url": "https://www.youtube.com/img/desktop/yt_1200.png",
"proxy_url": "https://images-ext-1.discordapp.net/external/Y9ec_ju_jMFXEYbE-Ie5kPp5R5im0556dCBV7EPvn8M/https/www.youtube.com/img/desktop/yt_1200.png",
"width": 1200,
"height": 1200
}
}
],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "https://youtube.com"
},
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256128810123335",
"createdTimestamp": 1662126323655,
"type": 0,
"system": false,
"content": "test 2",
"authorId": "530963824396992514",
"pinned": false,
"tts": false,
"nonce": "1015256087244308480",
"embeds": [],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "test 2"
}
],
[
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256083968835594",
"createdTimestamp": 1662126312964,
"type": 0,
"system": false,
"content": "https://whatsapp.com",
"authorId": "755312683632427120",
"pinned": false,
"tts": false,
"nonce": "1015256042948263936",
"embeds": [
{
"type": "link",
"url": "https://whatsapp.com/",
"title": "WhatsApp",
"description": "WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.",
"color": 1812113,
"provider": {
"name": "WhatsApp.com"
},
"thumbnail": {
"url": "https://static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
"proxy_url": "https://images-ext-2.discordapp.net/external/6KlN83vXntceA4ZV7gjYQYA_paQh7uOmhGDYm7td1rQ/https/static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
"width": 1200,
"height": 630
}
}
],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "https://whatsapp.com"
},
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256016490856488",
"createdTimestamp": 1662126296876,
"type": 0,
"system": false,
"content": "test",
"authorId": "755312683632427120",
"pinned": false,
"tts": false,
"nonce": "1015255975403192320",
"embeds": [],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "test"
}
]
]
and i want to format it to something like:
[
[
[
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256144094175392",
"createdTimestamp": 1662126327299,
"type": 0,
"system": false,
"content": "https://youtube.com",
"authorId": "530963824396992514",
"pinned": false,
"tts": false,
"nonce": "1015256103077806080",
"embeds": [
{
"type": "link",
"url": "https://youtube.com/",
"title": "YouTube",
"description": "Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.",
"thumbnail": {
"url": "https://www.youtube.com/img/desktop/yt_1200.png",
"proxy_url": "https://images-ext-1.discordapp.net/external/Y9ec_ju_jMFXEYbE-Ie5kPp5R5im0556dCBV7EPvn8M/https/www.youtube.com/img/desktop/yt_1200.png",
"width": 1200,
"height": 1200
}
}
],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "https://youtube.com"
}
],
[
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256128810123335",
"createdTimestamp": 1662126323655,
"type": 0,
"system": false,
"content": "test 2",
"authorId": "530963824396992514",
"pinned": false,
"tts": false,
"nonce": "1015256087244308480",
"embeds": [],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "test 2"
}
]
],
[
[
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256083968835594",
"createdTimestamp": 1662126312964,
"type": 0,
"system": false,
"content": "https://whatsapp.com",
"authorId": "755312683632427120",
"pinned": false,
"tts": false,
"nonce": "1015256042948263936",
"embeds": [
{
"type": "link",
"url": "https://whatsapp.com/",
"title": "WhatsApp",
"description": "WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.",
"color": 1812113,
"provider": {
"name": "WhatsApp.com"
},
"thumbnail": {
"url": "https://static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
"proxy_url": "https://images-ext-2.discordapp.net/external/6KlN83vXntceA4ZV7gjYQYA_paQh7uOmhGDYm7td1rQ/https/static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
"width": 1200,
"height": 630
}
}
],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "https://whatsapp.com"
}
],
[
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256016490856488",
"createdTimestamp": 1662126296876,
"type": 0,
"system": false,
"content": "test",
"authorId": "755312683632427120",
"pinned": false,
"tts": false,
"nonce": "1015255975403192320",
"embeds": [],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "test"
}
]
]
]
The ideas is that each filtered object is wrapped by an array, so I tried this:
const linkMessage = groupedMessages.flatMap((arrMessage) => arrMessage).some((message) => isValidURL(message.content));
const embedMessage = groupedMessages.flatMap((arrMessage) => arrMessage).some((message) => message.embeds.length > 0 && message.embeds.map((emb) => emb.type === 'rich'));
const componentMessage = groupedMessages.flatMap((arrMessage) => arrMessage).some((message) => message.components.length > 0);
const responseField = [];
if (linkMessage) {
responseField.push(
groupedMessages.map(
(arrMessage) =>
`from ${userMention(arrMessage[0].author.id)}\n${arrMessage
.filter((message) => isValidURL(message.content))
.map((message) => `${message.content} (sent at ${time(new Date(message.createdTimestamp), TimestampStyles.RelativeTime)})\n`)
.join('')}`,
),
);
}
if (embedMessage || componentMessage) {
responseField.push(groupedMessages.map((arrMessage) => `from ${userMention(arrMessage[0].author.id)}\n${italic('No content, maybe an embed or a component.')}`));
}
but the expected output isn't same with what I wanted. I just want to create a nested array format. Can anyone help me?
EDIT
I simplify the case:
[
[
{
"id": "1",
"content": "https://youtube.com",
"authorId": "1",
"embeds": [...
]
},
{
"id": "2",
"content": "lorem ipsum.",
"authorId": "1",
"embeds": []
},
{
"id": "3",
"content": "",
"authorId": "1",
"embeds": []
}
],
[
{
"id": "1",
"content": "https://whatsapp.com",
"authorId": "2",
"embeds": [...
]
},
{
"id": "2",
"content": "lorem ipsum.",
"authorId": "2",
"embeds": []
},
{
"id": "3",
"content": "",
"authorId": "2",
"embeds": []
}
]
]
expected output:
[
[
// Link type messages (content is valid URL)
[
{
"id": "1",
"content": "https://youtube.com",
"authorId": "1",
"embeds": [
{
"type": "link"
}
]
}
],
// regular type messages (empty embeds data)
[
{
"id": "2",
"content": "lorem ipsum.",
"authorId": "1",
"embeds": []
}
],
// Embed type messages (empty content)
[
{
"id": "3",
"content": "",
"authorId": "1",
"embeds": [
{
"type": "rich"
}
]
}
]
],
[...
]
]
You want to wrap every element with an array. Let's iterate the array "recursively" (it's just two levels really) looking for arrays, until we find a non-array then we wrap it and place it in place of arr[index].
Update:
no need for recursion since it's a known structure
we group sub-array items into object by type ("Link", "Regular" or "Empty")
finally we take the values of that object as the required array
update parent array in place
var msgs = [
[{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256144094175392",
"createdTimestamp": 1662126327299,
"type": 0,
"system": false,
"content": "https://youtube.com",
"authorId": "530963824396992514",
"pinned": false,
"tts": false,
"nonce": "1015256103077806080",
"embeds": [{
"type": "link",
"url": "https://youtube.com/",
"title": "YouTube",
"description": "Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.",
"thumbnail": {
"url": "https://www.youtube.com/img/desktop/yt_1200.png",
"proxy_url": "https://images-ext-1.discordapp.net/external/Y9ec_ju_jMFXEYbE-Ie5kPp5R5im0556dCBV7EPvn8M/https/www.youtube.com/img/desktop/yt_1200.png",
"width": 1200,
"height": 1200
}
}],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "https://youtube.com"
},
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256128810123335",
"createdTimestamp": 1662126323655,
"type": 0,
"system": false,
"content": "test 2",
"authorId": "530963824396992514",
"pinned": false,
"tts": false,
"nonce": "1015256087244308480",
"embeds": [],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "test 2"
}
],
[{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256083968835594",
"createdTimestamp": 1662126312964,
"type": 0,
"system": false,
"content": "https://whatsapp.com",
"authorId": "755312683632427120",
"pinned": false,
"tts": false,
"nonce": "1015256042948263936",
"embeds": [{
"type": "link",
"url": "https://whatsapp.com/",
"title": "WhatsApp",
"description": "WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.",
"color": 1812113,
"provider": {
"name": "WhatsApp.com"
},
"thumbnail": {
"url": "https://static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
"proxy_url": "https://images-ext-2.discordapp.net/external/6KlN83vXntceA4ZV7gjYQYA_paQh7uOmhGDYm7td1rQ/https/static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
"width": 1200,
"height": 630
}
}],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "https://whatsapp.com"
},
{
"channelId": "862033838896185376",
"guildId": "791708642813411358",
"id": "1015256016490856488",
"createdTimestamp": 1662126296876,
"type": 0,
"system": false,
"content": "test",
"authorId": "755312683632427120",
"pinned": false,
"tts": false,
"nonce": "1015255975403192320",
"embeds": [],
"components": [],
"attachments": [],
"stickers": [],
"editedTimestamp": null,
"mentions": {
"everyone": false,
"users": [],
"roles": [],
"crosspostedChannels": [],
"repliedUser": null,
"members": [],
"channels": []
},
"webhookId": null,
"groupActivityApplicationId": null,
"applicationId": null,
"activity": null,
"flags": 0,
"reference": null,
"interaction": null,
"cleanContent": "test"
}
]
]
function get_type_of_object(obj) {
if (obj.content.startsWith("http://") || obj.content.startsWith("https://")) {
return "Link"
}
if (obj.embeds.length) {
return "Regular"
}
if (!obj.embeds.length) {
return "Empty"
}
}
function wrap_by_group(arr) {
arr.forEach(function(sub_arr, index) {
var collector = {}
sub_arr.forEach(function(item) {
var group = get_type_of_object(item);
collector[group] = collector[group] || [];
collector[group].push(item);
})
arr[index] = Object.values(collector);
})
}
wrap_by_group(msgs);
console.log(msgs)
.as-console-wrapper {
max-height: 100% !important;
}
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'm trying to output all of the customer id's within my JSON data. I am using ejs as my templating engine. So far I'm only able to succsefully output 1 customer id via:
<p><%= jsonOrderData.orders[0].customer.id %></p>
When I try to loop through each order I get Cannot read property 'id' of undefined
for loop to loop through
<% for (var i = 0; i < jsonOrderData.orders.length; i++) {%>
<p>Customer: <%= jsonOrderData.orders[i].customer.id %></p>
<% }; %>
If I remove the .id after customer the error then goes away. It then outputs
Customer:[object Object] 50 times which is the legth of the json data.
I don't understand why it's not working within the loop when adding .id when it works fine without the loop manually setting the index?
JSON DATA (Cut Down 2 Orders)
{
"orders": [
{
"id": 533078016054,
"email": "email#gmail.com",
"closed_at": null,
"created_at": "2018-08-10T05:03:36+01:00",
"updated_at": "2018-08-10T05:03:37+01:00",
"number": 52,
"note": "",
"token": "f4877048c08eb98180ee5fda34f978bc",
"gateway": "manual",
"test": false,
"total_price": "13.98",
"subtotal_price": "13.98",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "13.98",
"cart_token": null,
"buyer_accepts_marketing": false,
"name": "#MW1052",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "18.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": null,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-10T05:03:36+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1052,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "email#gmail.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/f4877048c08eb98180ee5fda34f978bc/authenticate?key=redacted",
"admin_graphql_api_id": "gid://shopify/Order/redacted",
"line_items": [
{
"id": 1350736445494,
"variant_id": 8725905539126,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss15",
"variant_title": "S / Bottle Green",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Bottle Green",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736445494",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
},
{
"id": 1350736478262,
"variant_id": 8725905440822,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss12",
"variant_title": "S / Heather Grey",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Heather Grey",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736478262",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"billing_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "Jogn Doe",
"country_code": "GB",
"province_code": null
},
"shipping_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "John Doe",
"country_code": "GB",
"province_code": null
},
"fulfillments": [],
"refunds": [],
"customer": {
"id": 556974014518,
"email": "email#gmail.com",
"accepts_marketing": false,
"created_at": "2018-06-26T00:26:55+01:00",
"updated_at": "2018-08-10T05:03:36+01:00",
"first_name": "John",
"last_name": "Doe",
"orders_count": 22,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 533078016054,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "",
"last_order_name": "#MW1052",
"admin_graphql_api_id": "gid://shopify/Customer/556974014518",
"default_address": {
"id": 601657278518,
"customer_id": 556974014518,
"first_name": "John",
"last_name": "Doe",
"company": null,
"address1": "17A Oaklands Business Centre",
"address2": "Elm Grove",
"city": "Worthing",
"province": null,
"country": "United Kingdom",
"zip": "BN11 5LH",
"phone": null,
"name": "John Doe",
"province_code": null,
"country_code": "GB",
"country_name": "United Kingdom",
"default": true
}
}
},
{
"id": 532977778742,
"email": "james#bungeedesign.com",
"closed_at": null,
"created_at": "2018-08-09T22:18:53+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"number": 51,
"note": "",
"token": "a292d75bd7011cf255a1bf236b23d0a5",
"gateway": "manual",
"test": false,
"total_price": "6.99",
"subtotal_price": "6.99",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "6.99",
"cart_token": null,
"buyer_accepts_marketing": true,
"name": "#MW1051",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "9.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": 1327759385,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-09T22:18:53+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1051,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "james#bungeedesign.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/a292d75bd7011cf255a1bf236b23d0a5/authenticate?key=9322877ce6ce34be2feeb127d73d0f89",
"admin_graphql_api_id": "gid://shopify/Order/532977778742",
"line_items": [
{
"id": 1350552453174,
"variant_id": 8725905408054,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss11",
"variant_title": "S / Black",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Black",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350552453174",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"fulfillments": [],
"refunds": [],
"customer": {
"id": 552537620534,
"email": "james#bungeedesign.com",
"accepts_marketing": true,
"created_at": "2018-06-15T10:44:13+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"first_name": "James",
"last_name": "Rogers",
"orders_count": 18,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 532977778742,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "password page, prospect",
"last_order_name": "#MW1051",
"admin_graphql_api_id": "gid://shopify/Customer/552537620534"
}
}
]
}
What you have runs fine. It might be possible that something is getting lost in translation or .id is at another level. My guess is that you are not setting the variable jsonOrderData as you are expecting.
If you do console.log(jsonOrderData); do you get what you expect?
This works fine:
const json = {
"orders": [
{
"id": 533078016054,
"email": "email#gmail.com",
"closed_at": null,
"created_at": "2018-08-10T05:03:36+01:00",
"updated_at": "2018-08-10T05:03:37+01:00",
"number": 52,
"note": "",
"token": "f4877048c08eb98180ee5fda34f978bc",
"gateway": "manual",
"test": false,
"total_price": "13.98",
"subtotal_price": "13.98",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "13.98",
"cart_token": null,
"buyer_accepts_marketing": false,
"name": "#MW1052",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "18.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": null,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-10T05:03:36+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1052,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "email#gmail.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/f4877048c08eb98180ee5fda34f978bc/authenticate?key=redacted",
"admin_graphql_api_id": "gid://shopify/Order/redacted",
"line_items": [
{
"id": 1350736445494,
"variant_id": 8725905539126,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss15",
"variant_title": "S / Bottle Green",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Bottle Green",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736445494",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
},
{
"id": 1350736478262,
"variant_id": 8725905440822,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss12",
"variant_title": "S / Heather Grey",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Heather Grey",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736478262",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"billing_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "Jogn Doe",
"country_code": "GB",
"province_code": null
},
"shipping_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "John Doe",
"country_code": "GB",
"province_code": null
},
"fulfillments": [],
"refunds": [],
"customer": {
"id": 556974014518,
"email": "email#gmail.com",
"accepts_marketing": false,
"created_at": "2018-06-26T00:26:55+01:00",
"updated_at": "2018-08-10T05:03:36+01:00",
"first_name": "John",
"last_name": "Doe",
"orders_count": 22,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 533078016054,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "",
"last_order_name": "#MW1052",
"admin_graphql_api_id": "gid://shopify/Customer/556974014518",
"default_address": {
"id": 601657278518,
"customer_id": 556974014518,
"first_name": "John",
"last_name": "Doe",
"company": null,
"address1": "17A Oaklands Business Centre",
"address2": "Elm Grove",
"city": "Worthing",
"province": null,
"country": "United Kingdom",
"zip": "BN11 5LH",
"phone": null,
"name": "John Doe",
"province_code": null,
"country_code": "GB",
"country_name": "United Kingdom",
"default": true
}
}
},
{
"id": 532977778742,
"email": "james#bungeedesign.com",
"closed_at": null,
"created_at": "2018-08-09T22:18:53+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"number": 51,
"note": "",
"token": "a292d75bd7011cf255a1bf236b23d0a5",
"gateway": "manual",
"test": false,
"total_price": "6.99",
"subtotal_price": "6.99",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "6.99",
"cart_token": null,
"buyer_accepts_marketing": true,
"name": "#MW1051",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "9.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": 1327759385,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-09T22:18:53+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1051,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "james#bungeedesign.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/a292d75bd7011cf255a1bf236b23d0a5/authenticate?key=9322877ce6ce34be2feeb127d73d0f89",
"admin_graphql_api_id": "gid://shopify/Order/532977778742",
"line_items": [
{
"id": 1350552453174,
"variant_id": 8725905408054,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss11",
"variant_title": "S / Black",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Black",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350552453174",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"fulfillments": [],
"refunds": [],
"customer": {
"id": 552537620534,
"email": "james#bungeedesign.com",
"accepts_marketing": true,
"created_at": "2018-06-15T10:44:13+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"first_name": "James",
"last_name": "Rogers",
"orders_count": 18,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 532977778742,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "password page, prospect",
"last_order_name": "#MW1051",
"admin_graphql_api_id": "gid://shopify/Customer/552537620534"
}
}
]
};
for (let i = 0; i < json.orders.length; i++) {
const order = json.orders[i];
console.log(order.customer.id);
}
I am trying to sort an array of objects using underscore sortBy method the json is as follows
[
{
"styleId": 91,
"styleName": "Style Label",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 1,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": true,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": true,
"styleDesign": null,
"createdBy": "real",
"createdDate": 1494217733790,
"modifiedBy": "superuser",
"modifiedDate": 1494388952450,
"rowVersion": "AAAAAAIC8ls="
},
{
"styleId": 69,
"styleName": "irtest",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 16,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": false,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": false,
"styleDesign": null,
"createdBy": "arun",
"createdDate": 1493288218843,
"modifiedBy": "real",
"modifiedDate": 1494062410107,
"rowVersion": "AAAAAAHZaDk="
},
{
"styleId": 21,
"styleName": "new style-copy",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 5,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": false,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": true,
"styleDesign": null,
"createdBy": "Nandita",
"createdDate": 1493186162607,
"modifiedBy": "Nandita",
"modifiedDate": 1493186173807,
"rowVersion": "AAAAAAEXEwI="
},
{
"styleId": 97,
"styleName": "style 1",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 1,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": true,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": true,
"styleDesign": null,
"createdBy": "real",
"createdDate": 1494646737753,
"modifiedBy": "real",
"modifiedDate": 1494647127567,
"rowVersion": "AAAAAAIxLKM="
}
]
This is my sample json I am trying to sort this json by the field styleName like`
var result = _.sortBy(ctrl.styles, function (o) { return o.styleName; });
Result am getting is as follows
[
{
"styleId": 21,
"styleName": "new style-copy",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 5,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": false,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": true,
"styleDesign": null,
"createdBy": "Nandita",
"createdDate": 1493186162607,
"modifiedBy": "Nandita",
"modifiedDate": 1493186173807,
"rowVersion": "AAAAAAEXEwI="
},
{
"styleId": 69,
"styleName": "irtest",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 16,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": false,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": false,
"styleDesign": null,
"createdBy": "arun",
"createdDate": 1493288218843,
"modifiedBy": "real",
"modifiedDate": 1494062410107,
"rowVersion": "AAAAAAHZaDk="
},
{
"styleId": 91,
"styleName": "Style Label",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 1,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": true,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": true,
"styleDesign": null,
"createdBy": "real",
"createdDate": 1494217733790,
"modifiedBy": "superuser",
"modifiedDate": 1494388952450,
"rowVersion": "AAAAAAIC8ls="
},
{
"styleId": 97,
"styleName": "style 1",
"dataSourceId": 1,
"dataSourceName": null,
"stationeryId": 1,
"stationeryName": null,
"styleType": 1,
"styleTypeName": "Labels",
"isActive": true,
"isPlainPaper": true,
"isSystemMaintained": false,
"isPublished": true,
"designerUrl": null,
"sourceStyleId": 0,
"rowIndicatorCode": 2,
"isDefault": null,
"hasElement": true,
"styleDesign": null,
"createdBy": "real",
"createdDate": 1494646737753,
"modifiedBy": "real",
"modifiedDate": 1494647127567,
"rowVersion": "AAAAAAIxLKM="
}
]
where ctrl.styles is the above JSON, Is there something am doing wrong?
var result = _.sortBy(ctrl.styles, function (a) { return a.styleName.toUpperCase(); });
The problem I was facing was the styleName where having different case, converting styleName to uppercase solved the problem. Yashar's answer also solved the issue
With using this link and correcting return value, I found this works for me:(I suppresed array and named it as arr instead of ctrl.styles)
var res = _.sortBy(arr, function (a) {
var x= _.map(a.styleName.split(''), function (i) {
return i.charCodeAt(0);
}).join('');
return x;
});
or as #ArunBabuVijayanath said in comments:
var res = _.sortBy(arr, function (a) {
return a.styleName.toUpperCase();
});
I got this JSON. I want to get the value of "resource_uri" that is "/api/v1/client/2/".
I'm using Backbone/javascript.
json['resource_uri'] does not work.
The JSON is:
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"id": 2,
"nom": "",
"resource_uri": "/api/v1/client/2/",
"telefon": "",
"user": {
"date_joined": "2013-05-15T12:28:40",
"first_name": "",
"id": 51,
"is_active": true,
"is_staff": false,
"last_login": "2013-05-16T06:20:43",
"last_name": "",
"resource_uri": "/api/v1/user/51/",
"username": "gli"
}
}
]
}
Thanks in advance.
The value you're looking for, is in the objects array in the JSON, but it's in an object which is the first in an array:
var jsonVar = {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"id": 2, "nom": "", "resource_uri": "/api/v1/client/2/", "telefon": "", "user": {"date_joined": "2013-05-15T12:28:40", "first_name": "", "id": 51, "is_active": true, "is_staff": false, "last_login": "2013-05-16T06:20:43", "last_name": "", "resource_uri": "/api/v1/user/51/", "username": "gli"}}]}
alert(jsonVar.objects[0].resource_uri);
See here:
http://jsfiddle.net/SpAm/tnWmL/