Related
I'm getting a response from an API, I'm interested only in one of the link that returns. I have been using for a while
["data"]["tasks"]["0"]["result"]["files"]["0"]["url"]
to get the URL but it seems the API has changed and now the "result" it changes the position 0 in every call...
{"data": {
"id": "dcd99049-63b2",
"tag": "jobbuilder",
"status": "finished",
"created_at": "2022-11-22T21:57:28+00:00",
"started_at": "2022-11-22T21:57:28+00:00",
"ended_at": "2022-11-22T21:57:33+00:00",
"tasks": [
{
"id": "48c34a03-54f2",
"name": "task-2",
"job_id": "dcd99049-63b2",
"status": "finished",
"credits": 0,
"code": null,
"message": null,
"percent": 100,
"operation": "convert",
"engine": "qpdf",
"engine_version": "10.1.0",
"result": {
"files": [
{
"filename": "something.pdf",
"size": 633487
}
]
},
"created_at": "2022-11-22T21:57:30+00:00",
"started_at": "2022-11-22T21:57:32+00:00",
"ended_at": "2022-11-22T21:57:32+00:00",
"retry_of_task_id": null,
"copy_of_task_id": "dd64385a-a2e9",
"user_id": 6070,
"priority": 10,
"host_name": "meggie",
"storage": null,
"depends_on_task_ids": [
"dd64385a-a2e9",
"acfd2a2c-3c45"
],
"links": {
"self": "https://api.cloudconvert.com/v2/tasks/48c34a03-54f2"
}
},
{
"id": "6333e3b8-2f6f",
"name": "export-1",
"job_id": "dcd99049-63b2",
"status": "finished",
"credits": 0,
"code": null,
"message": null,
"percent": 100,
"operation": "export/url",
"result": {
"files": [
{
"filename": "something.pdf",
"size": 633487,
"url": "https://storage.cloudconvert.com/tasks/somethinglink.pdf"
}
]
},
"created_at": "2022-11-22T21:57:28+00:00",
"started_at": "2022-11-22T21:57:32+00:00",
"ended_at": "2022-11-22T21:57:32+00:00",
"retry_of_task_id": null,
"copy_of_task_id": null,
"user_id": 607,
"priority": 10,
"host_name": "meggie",
"storage": "ceph-fra",
"depends_on_task_ids": [
"48c34a03-54f2"
],
"links": {
"self": "https://api.cloudconvert.com/v2/tasks/6333e3b8-2f6f"
}
},
{
"id": "dd64385a-a2e9",
"name": "task-2-create-watermark",
"job_id": "dcd99049-63b2",
"status": "finished",
"credits": 1,
"code": null,
"message": null,
"percent": 100,
"operation": "watermark",
"engine": "imagemagick",
"engine_version": "7.1.0",
"result": {
"files": [
{
"filename": "watermark.pdf",
"size": 609229
}
]
},
"created_at": "2022-11-22T21:57:28+00:00",
"started_at": "2022-11-22T21:57:30+00:00",
"ended_at": "2022-11-22T21:57:32+00:00",
"retry_of_task_id": null,
"copy_of_task_id": null,
"user_id": 6070,
"priority": 10,
"host_name": "meggie",
"storage": "ceph-fra",
"depends_on_task_ids": [
"acfd2a2c-3c45-4e47"
],
"links": {
"self": "https://api.cloudconvert.com/v2/tasks/dd64385a-a2e9"
}
},
{
"id": "acfd2a2c-3c45-4e47",
"name": "task-1",
"job_id": "dcd99049-63b2",
"status": "finished",
"credits": 1,
"code": null,
"message": null,
"percent": 100,
"operation": "capture-website",
"engine": "wkhtml",
"engine_version": "0.12.5",
"result": {
"files": [
{
"filename": "something.pdf",
"size": 27330
}
]
},
"created_at": "2022-11-22T21:57:28+00:00",
"started_at": "2022-11-22T21:57:28+00:00",
"ended_at": "2022-11-22T21:57:30+00:00",
"retry_of_task_id": null,
"copy_of_task_id": null,
"user_id": 6070,
"priority": 10,
"host_name": "meggie",
"storage": null,
"depends_on_task_ids": [],
"links": {
"self": "https://api.cloudconvert.com/v2/tasks/acfd2a2c-3c45"
}
}
],
"links": {
"self": "https://api.cloudconvert.com/v2/jobs/dcd99049-63b2-443e"
}
}};
I would like to always extract only the link:
https://storage.cloudconvert.com/tasks/somethinglink.pdf
which position can change as mentioned before... The link always start with https://storage.cloudconvert.com
I have been using this for a while to access the first object in the array
["data"]["tasks"]["0"]["result"]["files"]["0"]["url"]
but it doesn't seem to work if the link it's in a different position...
This code extracts all values as strings, then finds the one with the necessary prefix:
const data = {"data":{"id":"dcd99049-63b2","tag":"jobbuilder","status":"finished","created_at":"2022-11-22T21:57:28+00:00","started_at":"2022-11-22T21:57:28+00:00","ended_at":"2022-11-22T21:57:33+00:00","tasks":[{"id":"48c34a03-54f2","name":"task-2","job_id":"dcd99049-63b2","status":"finished","credits":0,"code":null,"message":null,"percent":100,"operation":"convert","engine":"qpdf","engine_version":"10.1.0","result":{"files":[{"filename":"something.pdf","size":633487}]},"created_at":"2022-11-22T21:57:30+00:00","started_at":"2022-11-22T21:57:32+00:00","ended_at":"2022-11-22T21:57:32+00:00","retry_of_task_id":null,"copy_of_task_id":"dd64385a-a2e9","user_id":6070,"priority":10,"host_name":"meggie","storage":null,"depends_on_task_ids":["dd64385a-a2e9","acfd2a2c-3c45"],"links":{"self":"https://api.cloudconvert.com/v2/tasks/48c34a03-54f2"}},{"id":"6333e3b8-2f6f","name":"export-1","job_id":"dcd99049-63b2","status":"finished","credits":0,"code":null,"message":null,"percent":100,"operation":"export/url","result":{"files":[{"filename":"something.pdf","size":633487,"url":"https://storage.cloudconvert.com/tasks/somethinglink.pdf"}]},"created_at":"2022-11-22T21:57:28+00:00","started_at":"2022-11-22T21:57:32+00:00","ended_at":"2022-11-22T21:57:32+00:00","retry_of_task_id":null,"copy_of_task_id":null,"user_id":607,"priority":10,"host_name":"meggie","storage":"ceph-fra","depends_on_task_ids":["48c34a03-54f2"],"links":{"self":"https://api.cloudconvert.com/v2/tasks/6333e3b8-2f6f"}},{"id":"dd64385a-a2e9","name":"task-2-create-watermark","job_id":"dcd99049-63b2","status":"finished","credits":1,"code":null,"message":null,"percent":100,"operation":"watermark","engine":"imagemagick","engine_version":"7.1.0","result":{"files":[{"filename":"watermark.pdf","size":609229}]},"created_at":"2022-11-22T21:57:28+00:00","started_at":"2022-11-22T21:57:30+00:00","ended_at":"2022-11-22T21:57:32+00:00","retry_of_task_id":null,"copy_of_task_id":null,"user_id":6070,"priority":10,"host_name":"meggie","storage":"ceph-fra","depends_on_task_ids":["acfd2a2c-3c45-4e47"],"links":{"self":"https://api.cloudconvert.com/v2/tasks/dd64385a-a2e9"}},{"id":"acfd2a2c-3c45-4e47","name":"task-1","job_id":"dcd99049-63b2","status":"finished","credits":1,"code":null,"message":null,"percent":100,"operation":"capture-website","engine":"wkhtml","engine_version":"0.12.5","result":{"files":[{"filename":"something.pdf","size":27330}]},"created_at":"2022-11-22T21:57:28+00:00","started_at":"2022-11-22T21:57:28+00:00","ended_at":"2022-11-22T21:57:30+00:00","retry_of_task_id":null,"copy_of_task_id":null,"user_id":6070,"priority":10,"host_name":"meggie","storage":null,"depends_on_task_ids":[],"links":{"self":"https://api.cloudconvert.com/v2/tasks/acfd2a2c-3c45"}}],"links":{"self":"https://api.cloudconvert.com/v2/jobs/dcd99049-63b2-443e"}}}
const f=i=>i instanceof Object?Object.values(i).flatMap(v=>f(v)):[i+'']
console.log(f(data).find(i=>
i.startsWith('https://storage.cloudconvert.com/tasks/')))
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)
Let's say I have this object
[{
"id": 2,
"email": "admin#example.com",
"role_id": 1,
"is_active": 1,
"created_at": "2020-10-10T17:05:34.000000Z",
"updated_at": "2020-10-10T17:05:34.000000Z",
"deleted_at": null
}, {
"id": 3,
"email": "agency_owner#example.com",
"role_id": 2,
"is_active": 1,
"created_at": "2020-10-11T18:30:06.000000Z",
"updated_at": "2020-10-11T18:33:51.000000Z",
"deleted_at": null
}]
I would get another object:
[{
"value": 2,
"text": "admin#example.com",
}, {
"value": 3,
"text": "agency_owner#example.com",
}, {
"value": 4,
"text": "license_owner#example.com",
}]
So, renaming "id" with "value" and "email" with "text".
I would use map and maybe not installing lodash or similar...
Thank you...
Well, map is a great idea. What is stopping you from using it?
You can:
obj = [{
"id": 2,
"email": "admin#example.com",
"role_id": 1,
"is_active": 1,
"created_at": "2020-10-10T17:05:34.000000Z",
"updated_at": "2020-10-10T17:05:34.000000Z",
"deleted_at": null
}, {
"id": 3,
"email": "agency_owner#example.com",
"role_id": 2,
"is_active": 1,
"created_at": "2020-10-11T18:30:06.000000Z",
"updated_at": "2020-10-11T18:33:51.000000Z",
"deleted_at": null
}]
obj = obj.map(e => { return {
value: e.id,
text: e.email
}})
console.log(obj)
You can use map as you mentioned:
var arr = [{
"id": 2,
"email": "admin#example.com",
"role_id": 1,
"is_active": 1,
"created_at": "2020-10-10T17:05:34.000000Z",
"updated_at": "2020-10-10T17:05:34.000000Z",
"deleted_at": null
}, {
"id": 3,
"email": "agency_owner#example.com",
"role_id": 2,
"is_active": 1,
"created_at": "2020-10-11T18:30:06.000000Z",
"updated_at": "2020-10-11T18:33:51.000000Z",
"deleted_at": null
}];
var result = arr.map(o => {
return { value: o.id, email: o.email}
});
console.log(result);
[{
"id": 2,
"email": "admin#example.com",
"role_id": 1,
"is_active": 1,
"created_at": "2020-10-10T17:05:34.000000Z",
"updated_at": "2020-10-10T17:05:34.000000Z",
"deleted_at": null
}, {
"id": 3,
"email": "agency_owner#example.com",
"role_id": 2,
"is_active": 1,
"created_at": "2020-10-11T18:30:06.000000Z",
"updated_at": "2020-10-11T18:33:51.000000Z",
"deleted_at": null
}].map(function(obj){
return {
value:obj.id,
text:obj.email
}
})
Javascript newbie here :) I want to achieve sth but can't figure it out.
Here is my data .
<pre>
[
[
{
"id": 2759178563,
"title": "Ergonomic Paper Computer",
"handle": "ergonomic-paper-computer",
"body_html": "Enable turn-key infrastructures",
"published_at": "2015-09-23T20:51:49-04:00",
"created_at": "2015-09-23T20:51:49-04:00",
"updated_at": "2015-09-23T20:51:49-04:00",
"vendor": "Schinner Inc",
"product_type": "Computer",
"tags": [
"Computer",
"Ergonomic",
"Paper"
],
"variants": [
{
"id": 8041863299,
"title": "White",
"option1": "White",
"option2": null,
"option3": null,
"price": "67.25",
"grams": 5145,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 1,
"product_id": 2759178563,
"created_at": "2015-09-23T20:51:49-04:00",
"updated_at": "2015-09-23T20:51:49-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041863363,
"title": "Mint green",
"option1": "Mint green",
"option2": null,
"option3": null,
"price": "29.58",
"grams": 6860,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 2,
"product_id": 2759178563,
"created_at": "2015-09-23T20:51:49-04:00",
"updated_at": "2015-09-23T20:51:49-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041863491,
"title": "Yellow",
"option1": "Yellow",
"option2": null,
"option3": null,
"price": "54.19",
"grams": 6045,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 3,
"product_id": 2759178563,
"created_at": "2015-09-23T20:51:49-04:00",
"updated_at": "2015-09-23T20:51:49-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041863555,
"title": "Blue",
"option1": "Blue",
"option2": null,
"option3": null,
"price": "22.88",
"grams": 9526,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 4,
"product_id": 2759178563,
"created_at": "2015-09-23T20:51:49-04:00",
"updated_at": "2015-09-23T20:51:49-04:00",
"available": true,
"featured_image": null
}
],
"images": [
{
"id": 5642046019,
"created_at": "2015-09-23T20:51:49-04:00",
"position": 1,
"updated_at": "2015-09-23T20:51:49-04:00",
"product_id": 2759178563,
"variant_ids": [],
"src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Ergonomic_20Paper_20Computer.png?v=1443055909"
}
],
"options": [
{
"name": "Title",
"position": 1,
"values": [
"White",
"Mint green",
"Yellow",
"Blue"
]
}
]
},
{
"id": 2759192387,
"title": "Heavy Duty Concrete Keyboard",
"handle": "heavy-duty-concrete-keyboard",
"body_html": "Strategize synergistic e-markets",
"published_at": "2015-09-23T20:52:07-04:00",
"created_at": "2015-09-23T20:52:07-04:00",
"updated_at": "2015-09-23T20:52:07-04:00",
"vendor": "Stiedemann and Sons",
"product_type": "Keyboard",
"tags": [
"Concrete",
"Duty",
"Heavy",
"Keyboard"
],
"variants": [
{
"id": 8041883779,
"title": "Magenta",
"option1": "Magenta",
"option2": null,
"option3": null,
"price": "14.20",
"grams": 3030,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 1,
"product_id": 2759192387,
"created_at": "2015-09-23T20:52:07-04:00",
"updated_at": "2015-09-23T20:52:07-04:00",
"available": true,
"featured_image": null
}
],
"images": [
{
"id": 5642056899,
"created_at": "2015-09-23T20:52:07-04:00",
"position": 1,
"updated_at": "2015-09-23T20:52:07-04:00",
"product_id": 2759192387,
"variant_ids": [],
"src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Heavy_20Duty_20Concrete_20Keyboard.png?v=1443055927"
}
],
"options": [
{
"name": "Title",
"position": 1,
"values": [
"Magenta"
]
}
]
}
],
[
{
"id": 2759168323,
"title": "Awesome Cotton Computer",
"handle": "awesome-cotton-computer-1",
"body_html": "Brand synergistic applications",
"published_at": "2015-09-23T20:51:24-04:00",
"created_at": "2015-09-23T20:51:24-04:00",
"updated_at": "2015-09-23T20:51:24-04:00",
"vendor": "Hills Group",
"product_type": "Computer",
"tags": [
"Awesome",
"Computer",
"Cotton"
],
"variants": [
{
"id": 8041841795,
"title": "Black",
"option1": "Black",
"option2": null,
"option3": null,
"price": "2.05",
"grams": 1906,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 1,
"product_id": 2759168323,
"created_at": "2015-09-23T20:51:24-04:00",
"updated_at": "2015-09-23T20:51:24-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041841859,
"title": "Orchid",
"option1": "Orchid",
"option2": null,
"option3": null,
"price": "10.78",
"grams": 4970,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 2,
"product_id": 2759168323,
"created_at": "2015-09-23T20:51:24-04:00",
"updated_at": "2015-09-23T20:51:24-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041841923,
"title": "Tan",
"option1": "Tan",
"option2": null,
"option3": null,
"price": "50.54",
"grams": 6738,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 3,
"product_id": 2759168323,
"created_at": "2015-09-23T20:51:24-04:00",
"updated_at": "2015-09-23T20:51:24-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041841987,
"title": "Teal",
"option1": "Teal",
"option2": null,
"option3": null,
"price": "91.51",
"grams": 8718,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 4,
"product_id": 2759168323,
"created_at": "2015-09-23T20:51:24-04:00",
"updated_at": "2015-09-23T20:51:24-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041842051,
"title": "Gold",
"option1": "Gold",
"option2": null,
"option3": null,
"price": "8.24",
"grams": 194,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 5,
"product_id": 2759168323,
"created_at": "2015-09-23T20:51:24-04:00",
"updated_at": "2015-09-23T20:51:24-04:00",
"available": true,
"featured_image": null
}
],
"images": [
{
"id": 5642032131,
"created_at": "2015-09-23T20:51:24-04:00",
"position": 1,
"updated_at": "2015-09-23T20:51:24-04:00",
"product_id": 2759168323,
"variant_ids": [],
"src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Awesome_20Cotton_20Computer_f74fc2a4-efa5-42ca-a3b2-36c378f1c003.png?v=1443055884"
}
],
"options": [
{
"name": "Title",
"position": 1,
"values": [
"Black",
"Orchid",
"Tan",
"Teal",
"Gold"
]
}
]
},
{
"id": 2759192387,
"title": "Heavy Duty Concrete Keyboard",
"handle": "heavy-duty-concrete-keyboard",
"body_html": "Strategize synergistic e-markets",
"published_at": "2015-09-23T20:52:07-04:00",
"created_at": "2015-09-23T20:52:07-04:00",
"updated_at": "2015-09-23T20:52:07-04:00",
"vendor": "Stiedemann and Sons",
"product_type": "Keyboard",
"tags": [
"Concrete",
"Duty",
"Heavy",
"Keyboard"
],
"variants": [
{
"id": 8041883779,
"title": "Magenta",
"option1": "Magenta",
"option2": null,
"option3": null,
"price": "14.20",
"grams": 3030,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 1,
"product_id": 2759192387,
"created_at": "2015-09-23T20:52:07-04:00",
"updated_at": "2015-09-23T20:52:07-04:00",
"available": true,
"featured_image": null
}
],
"images": [
{
"id": 5642056899,
"created_at": "2015-09-23T20:52:07-04:00",
"position": 1,
"updated_at": "2015-09-23T20:52:07-04:00",
"product_id": 2759192387,
"variant_ids": [],
"src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Heavy_20Duty_20Concrete_20Keyboard.png?v=1443055927"
}
],
"options": [
{
"name": "Title",
"position": 1,
"values": [
"Magenta"
]
}
]
}
],
[
{
"id": 2759167747,
"title": "Awesome Bronze Computer",
"handle": "awesome-bronze-computer",
"body_html": "Orchestrate holistic web services",
"published_at": "2015-09-23T20:51:20-04:00",
"created_at": "2015-09-23T20:51:20-04:00",
"updated_at": "2015-09-23T20:51:20-04:00",
"vendor": "Zboncak-Kemmer",
"product_type": "Computer",
"tags": [
"Awesome",
"Bronze",
"Computer"
],
"variants": [
{
"id": 8041840195,
"title": "Magenta",
"option1": "Magenta",
"option2": null,
"option3": null,
"price": "56.69",
"grams": 6035,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 1,
"product_id": 2759167747,
"created_at": "2015-09-23T20:51:20-04:00",
"updated_at": "2015-09-23T20:51:20-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041840259,
"title": "Mint green",
"option1": "Mint green",
"option2": null,
"option3": null,
"price": "63.89",
"grams": 9961,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 2,
"product_id": 2759167747,
"created_at": "2015-09-23T20:51:20-04:00",
"updated_at": "2015-09-23T20:51:20-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041840323,
"title": "Maroon",
"option1": "Maroon",
"option2": null,
"option3": null,
"price": "18.76",
"grams": 922,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 3,
"product_id": 2759167747,
"created_at": "2015-09-23T20:51:20-04:00",
"updated_at": "2015-09-23T20:51:20-04:00",
"available": true,
"featured_image": null
},
{
"id": 8041840387,
"title": "Salmon",
"option1": "Salmon",
"option2": null,
"option3": null,
"price": "97.60",
"grams": 1355,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 4,
"product_id": 2759167747,
"created_at": "2015-09-23T20:51:20-04:00",
"updated_at": "2015-09-23T20:51:20-04:00",
"available": true,
"featured_image": null
}
],
"images": [
{
"id": 5642031235,
"created_at": "2015-09-23T20:51:20-04:00",
"position": 1,
"updated_at": "2015-09-23T20:51:20-04:00",
"product_id": 2759167747,
"variant_ids": [],
"src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Awesome_20Bronze_20Computer.png?v=1443055880"
}
],
"options": [
{
"name": "Title",
"position": 1,
"values": [
"Magenta",
"Mint green",
"Maroon",
"Salmon"
]
}
]
},
{
"id": 2759192387,
"title": "Heavy Duty Concrete Keyboard",
"handle": "heavy-duty-concrete-keyboard",
"body_html": "Strategize synergistic e-markets",
"published_at": "2015-09-23T20:52:07-04:00",
"created_at": "2015-09-23T20:52:07-04:00",
"updated_at": "2015-09-23T20:52:07-04:00",
"vendor": "Stiedemann and Sons",
"product_type": "Keyboard",
"tags": [
"Concrete",
"Duty",
"Heavy",
"Keyboard"
],
"variants": [
{
"id": 8041883779,
"title": "Magenta",
"option1": "Magenta",
"option2": null,
"option3": null,
"price": "14.20",
"grams": 3030,
"compare_at_price": null,
"sku": "",
"requires_shipping": true,
"taxable": true,
"position": 1,
"product_id": 2759192387,
"created_at": "2015-09-23T20:52:07-04:00",
"updated_at": "2015-09-23T20:52:07-04:00",
"available": true,
"featured_image": null
}
],
"images": [
{
"id": 5642056899,
"created_at": "2015-09-23T20:52:07-04:00",
"position": 1,
"updated_at": "2015-09-23T20:52:07-04:00",
"product_id": 2759192387,
"variant_ids": [],
"src": "https://cdn.shopify.com/s/files/1/1000/7970/products/Heavy_20Duty_20Concrete_20Keyboard.png?v=1443055927"
}
],
"options": [
{
"name": "Title",
"position": 1,
"values": [
"Magenta"
]
}
]
}
]
]
</pre>
And here is my code:
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
#Injectable()
export class ShopifyService {
/**
* Initialization
*/
constructor (
private http: Http
) {}
private shopifyUrl = 'app/heroes.json';
errorMessage: string;
/**
* Private Methods
*/
fetchProducts(): Promise<Response> {
return this.http.get(this.shopifyUrl)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
if (body.data) {
return body.data;
}
else if (body.products) {
return body.products;
}
else {
return { };
}
}
private handleError (error: any) {
let errMsg = error.message || 'Server error';
console.error(errMsg);
return Promise.reject(errMsg);
}
private filterProducts(list, archetype) {
var result = [];
for (var i = 0; i < list.length; i++) {
if (list[i].product_type === archetype) {
result.push(list[i]);
}
}
return result;
}
/**
* Public Methods
*/
public findProducts(archetypes) {
return this.fetchProducts().then(
products => {
var result = [],
fetchedResponse = [];
for (var i = 0; i < archetypes.length; i++) {
fetchedResponse = this.filterProducts(
products, archetypes[i]
);
result = result.concat(fetchedResponse);
}
return result;
},
error => this.errorMessage = <any>error
)
}
public findSingleProductVariant() {
var result = [],
j = 0;
return this.findVariants().then(
product => {
for (var i = 0; i < product.length; i++) {
// console.log(product[i]);
}
}
);
// return result;
}
findVariants() {
return this.findProducts(['Computer', 'Keyboard']).then(
products => {
var result = [];
for (var i = 0; i < products.length; i++) {
if (products[i].product_type === 'Computer') {
for (var j = 0; j < products.length; j++) {
if (products[j].product_type === 'Keyboard') {
result.push([products[i], products[j]]);
}
}
}
}
console.log(result);
return result;
}
)
}
}
Until here I got to half of what. An array of two dimensional arrays (one of them is from keyboard type and another one from computer type).
It is sth like this ==>
[
[
[Computer_A],
[Keyboard_A]
],
[
[Computer_B],
[Keyboard_A]
],
[
[Computer_C],
[Keyboard_A]
],
]
Now each one of these objects have its own array of variants. I have to modify my findSingleProductVariant in order to go over each one of these arrays, pick a keyboard variant (which its array has a price field), also pick a computer variant and calculate the price. If the price is less than 1000, it can continue picking another keyboard and computer. But the thing is that it can't have two identical arrays. for instance we can't have sth like this.
[
['Computer_A'], ['Keyboard_A'],
['Computer_A'], ['Keyboard_A'],
]
The key thing here is that you can't directly compare objects and expect relevant results, e.g.
['Red Lamp', 'Blue Table'] === ['Red Lamp', 'Blue Table']
will return false (Array.indexOf() also won't work as expected since it uses strict comparison).
So for an array of arrays, you will have to use two nested loops to get down to comparing primitive values.
I have two arrays like this :
var friendemail = [ {
"data": {
"status": "OK",
"message": "User list fetched successfully",
"userList": [
{
"userId": 1,
"emailId": "abc.com",
"firstName": "Abc",
"lastName": "Xyz",
"nickName": "Nic",
"type": "USER",
"apiKey": "355901361"
},
{
"userId": 2,
"emailId": "babitadhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 3,
"emailId": "testuser#g.com",
"firstName": "Test_User",
"lastName": "Account",
"nickName": "Testi",
"type": "USER",
"apiKey": "1403626362113"
},
{
"userId": 4,
"emailId": "dhami#gmail.com",
"firstName": "dhami",
"lastName": "Dhami",
"nickName": "bobby",
"type": "DEVELOPER",
"apiKey": "222234567"
},
{
"userId": 5,
"emailId": "babita.dhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "1403709178117"
},
{
"userId": 6,
"emailId": "Chris#abc.com",
"firstName": "dhami",
"lastName": "dhami",
"nickName": "dhami",
"type": "DEVELOPER",
"apiKey": "333234567"
},
{
"userId": 7,
"emailId": "kevin.wei#qdevinc.com",
"firstName": "abc",
"lastName": "xyz",
"nickName": "none",
"type": "DEVELOPER",
"apiKey": "111234567"
},
{
"userId": 8,
"emailId": "dhamji#gmail.com",
"firstName": "Bab",
"lastName": "Dham",
"nickName": "bobby",
"type": "USER",
"apiKey": "1403790266057"
},
{
"userId": 9,
"emailId": "info#hemlockhills.ca",
"firstName": "Jenn",
"lastName": "Becker",
"nickName": "JennB",
"type": "USER",
"apiKey": "355901361"
},
{
"userId": 10,
"emailId": "babitadhami1#gmail.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 11,
"emailId": "b.dhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 12,
"emailId": "dhami.babita#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 13,
"emailId": "Francie#abc.com",
"firstName": "Francie",
"lastName": "Francie",
"nickName": "Francie",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 14,
"emailId": "Sam#abc.com",
"firstName": "Sam",
"lastName": "M",
"nickName": "S",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 15,
"emailId": "Sid#abc.com",
"firstName": "Sid",
"lastName": "B",
"nickName": "S",
"type": "USER",
"apiKey": "22234567"
},
{
"userId": 16,
"emailId": "tim#outlook.com",
"firstName": "tim",
"lastName": "tim",
"nickName": "tim",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 17,
"emailId": "racing#gmail.com",
"firstName": "racing",
"lastName": "racing",
"nickName": "Hollywood",
"type": "USER",
"apiKey": "222234567"
}
]
},
"status": 200,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "OK"
}]
and another is
var deviceContactEmail = [
{
"id": "1",
"rawId": "1",
"displayName": "kandwal",
"name": {
"formatted": "kandwal",
"givenName": "kandwal"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "testuser#g.com",
"id": "6",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/1/photo",
"type": "url",
"id": "1",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "2",
"rawId": "2",
"displayName": "xyz",
"name": {
"formatted": "xyz ",
"givenName": "xyz"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "Chris#abc.com",
"id": "12",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/2/photo",
"type": "url",
"id": "7",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "3",
"rawId": "3",
"displayName": "cdf",
"name": {
"formatted": "cdf",
"givenName": "cdf"
},
"nickname": null,
"phoneNumbers": null,
"emails": null,
"addresses": [
{
"region": "Uk",
"id": "19",
"locality": "Dehra Dun",
"formatted": "dddd",
"type": "home",
"pref": false,
"country": "India"
}
],
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/3/photo",
"type": "url",
"id": "14",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "4",
"rawId": "4",
"displayName": "abcd",
"name": {
"formatted": "scd ",
"givenName": "scd"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "dhami#gmail.com",
"id": "26",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/4/photo",
"type": "url",
"id": "21",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "5",
"rawId": "5",
"displayName": "hiteshbhattcse#gmail.com",
"name": {
"formatted": "hiteshbhattcse#gmail.com ",
"givenName": "hiteshbhattcse#gmail.com"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "hiteshbhattcse#gmail.com",
"id": "33",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/5/photo",
"type": "url",
"id": "28",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "6",
"rawId": "6",
"displayName": "hitet#gmail.com",
"name": {
"formatted": "hitet#gmail.com ",
"givenName": "hitet#gmail.com"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "hiteshbhatt#gmail.com",
"id": "40",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/6/photo",
"type": "url",
"id": "35",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "7",
"rawId": "7",
"displayName": null,
"name": {
"formatted": ""
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "mayank.th088#gmail.com",
"id": "46",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/7/photo",
"type": "url",
"id": "41",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "8",
"rawId": "8",
"displayName": null,
"name": {
"formatted": ""
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "gcjoshi83#gmail.com",
"id": "53",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/8/photo",
"type": "url",
"id": "48",
"pref": false
}
],
"categories": null,
"urls": null
}]
I want to compare both of them for email id . and wanna get the common email id inside 1 array and rest in one array from deviceContactEmail.
I tried angular. each but not getting success.
var wUser = [];
var nonWUser = [];
angular.forEach(deviceContactEmail, function(phonevalue){
console.log(phonevalue);
angular.forEach(friendemail, function(value){
if (phonevalue.emails) {
if(phonevalue.emails[0].value === value.emailId){
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
}else{
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
nonWUser.push(phonevalue);
};
}
})
})
Hi Try this I solved to remove the duplicates value in the array check it...
var wUser = [];
var nonWUser = [];
angular.forEach(deviceContactEmail, function(phonevalue){
console.log(phonevalue);
angular.forEach(friendemail[0].data.userList, function (value) {
if (phonevalue.emails) {
if(phonevalue.emails[0].value === value.emailId){
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
}
else {
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
if ($scope.nonWUser.length == 0) {
nonWUser.push(phonevalue);
}
var filteredVal= $scope.nonWUser.filter(function (filterValue) {
return filterValue.emails[0].value == phonevalue.emails[0].value;
});
if (filteredVal.length == 0)
nonWUser.push(phonevalue);
}
}
});
});
check the edited file
It seem you are not pointing the inner loop at the right list. friendemail is a list but contains only one item. I assume the emailId you are testing for is buried inside the data which happens to be child of friendemail. Try the code below
angular.forEach(deviceContactEmail, function(phonevalue) {
console.log("................ ",phonevalue, " ", friendemail[0].data.userList.length);
angular.forEach(friendemail[0].data.userList, function(value) {
if (phonevalue.emails) {
if (phonevalue.emails[0].value === value.emailId) {
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
} else {
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
nonWUser.push(phonevalue);
}
;
}
})
})