Angular track by object.id - javascript

I have following JSON data received form REST api.
[
{
"names": {
"en": "test123"
},
"children": [],
"id": "68d87e8c-42f5-4f11-b25a-b30624246c3b",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test123",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
},
{
"names": {
"en": "test456"
},
"children": [],
"id": "d175e6d1-874e-4909-afb2-790c0a940c3f",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test456",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
}
]
I'm trying to display it using directive ng-repeat. Using track by object.id.
It is used like this:
<tr ng-repeat="chapter in chapters | filter: search track by chapter.id">
But the problem is that the ngRepeat:Dupes error still appear. I have checked the data contained in JSON, but there is no duplicite id in it. Do you know why the ngRepeat:Dupes error persists?

Based on the data given, no duplicate error is thrown, below is jsfiddle.
<div ng-controller="MainCtrl">
<input type="text" ng-model="search">
<div ng-repeat="chapter in chapters | filter: search track by chapter.id">{{chapter.id}}</div>
</div>
controller
$scope.chapters = [{
"names": {
"en": "test123"
},
"children": [],
"id": "68d87e8c-42f5-4f11-b25a-b30624246c3b",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test123",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
}, {
"names": {
"en": "test456"
},
"children": [],
"id": "d175e6d1-874e-4909-afb2-790c0a940c3f",
"version": 1,
"code": "0",
"order": 0,
"country": "HR",
"name": "test456",
"parent": null,
"selected": false,
"hasQuestions": false,
"level": 1,
"state": "original",
"hasChildChapters": false
}]
http://jsfiddle.net/75sdsuz2/2/

Related

Get Particular value from Json Using Javascript or Jquery

I need to get only name value from below Json using Javscript or Jquery.
From below json I need to get key name values-Automation1, Automation2, Automation3
{
"status": [
[{
"id": 3,
"orgId": 1,
"name": "Automation1",
"email": "",
"Url": "",
"memberCount": 101,
"permission": 0
}, {
"id": 5,
"orgId": 1,
"name": "Automation2",
"email": "",
"Url": "",
"memberCount": 13,
"permission": 0
}, {
"id": 12,
"orgId": 1,
"name": "Automation3",
"email": "",
"Url": "/",
"memberCount": 25,
"permission": 0
}]
]
}

How to solve SyntaxError: Unexpected token ^ in JSON at position error?

I am receiving a dynamic data string from the python kernel, (however, it's an object but the python kernel can only send it as a sting due to the limitation of the python backend that cant be changed due to a third-party package), below is the console.log output.
[{"model_class": "DataToolParameter", "name": "input_file", "argument": null, "type": "data", "label": "VCF/BCF Data", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": null, "extensions": ["vcf", "vcf_bgzip", "bcf"], "edam": {"edam_formats": ["format_3016", "format_3016", "format_3020"], "edam_data": ["data_0006", "data_0006", "data_3498"]}, "multiple": false, "options": {"hda": [], "hdca": []}, "default_value": null, "text_value": "No dataset."}, {"model_class": "Section", "name": "sec_required", "type": "section", "title": "Required References", "help": null, "expanded": true, "inputs": [{"model_class": "Conditional", "name": "reference_source", "type": "conditional", "cases": [{"model_class": "ConditionalWhen", "value": "cached", "inputs": [{"model_class": "SelectToolParameter", "name": "fasta_ref", "argument": null, "type": "select", "label": "Reference genome", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": true, "value": null, "options": [], "display": null, "multiple": false, "textable": false, "default_value": null, "text_value": "None"}]}, {"model_class": "ConditionalWhen", "value": "history", "inputs": [{"model_class": "DataToolParameter", "name": "fasta_ref", "argument": null, "type": "data", "label": "Reference genome", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "extensions": ["fasta"], "edam": {"edam_formats": ["format_1929"], "edam_data": ["data_2044"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as fasta)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta", "tags": [], "src": "hda", "keep": false}, {"id": "47f5e6f7acd01631", "hid": 3, "name": "Extract MAF blocks on data 2 (as fasta)", "tags": [], "src": "hda", "keep": false}, {"id": "695fd3e24b533dbc", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as fasta)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "text_value": "No dataset."}]}], "test_param": {"model_class": "SelectToolParameter", "name": "reference_source_selector", "argument": null, "type": "select", "label": "Choose the source for the reference genome", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": "cached", "options": [["Use a built-in genome", "cached", false], ["Use a genome from the history", "history", false]], "display": null, "multiple": false, "textable": false, "text_value": "Use a built-in genome"}}, {"model_class": "DataToolParameter", "name": "gff_annot", "argument": null, "type": "data", "label": "GFF3 annotation file", "help": "From Ensembl: ftp://ftp.ensembl.org/pub/current_gff3/", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": null, "extensions": ["gff3"], "edam": {"edam_formats": ["format_1975"], "edam_data": ["data_1255"]}, "multiple": false, "options": {"hda": [], "hdca": []}, "default_value": null, "text_value": "No dataset."}]}, {"model_class": "Section", "name": "sec_csq_opts", "type": "section", "title": "CSQ Options", "help": null, "expanded": true, "inputs": [{"model_class": "IntegerToolParameter", "name": "ncsq", "argument": null, "type": "integer", "label": "maximum number of consequences to consider per site", "help": "-ncsq 16", "refresh_on_change": false, "min": 1, "max": 50, "optional": false, "hidden": false, "is_dynamic": false, "value": "16", "area": false, "datalist": [], "default_value": "16", "text_value": "16"}, {"model_class": "BooleanToolParameter", "name": "local_csq", "argument": null, "type": "boolean", "label": "run localized predictions considering only one VCF record at a time", "help": "--local-csq switch off haplotype-aware calling, run localized predictions considering only one VCF record at a time", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "false", "truevalue": "--local-csq", "falsevalue": "", "default_value": "false", "text_value": "false"}, {"model_class": "SelectToolParameter", "name": "phase", "argument": null, "type": "select", "label": "phase", "help": "how to construct haplotypes and how to deal with unphased data", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "options": [["take GTs as is, create haplotypes regardless of phase (0/1 -> 0|1)", "a", false], ["merge *all* GTs into a single haplotype (0/1 -> 1, 1/2 -> 1)", "m", false], ["require phased GTs, throw an error on unphased het GTs", "r", false], ["create non-reference haplotypes if possible (0/1 -> 1|1, 1/2 -> 1|2)", "R", false], ["skip unphased GTs", "s", false]], "display": null, "multiple": false, "textable": false, "default_value": null, "text_value": "Nothing selected."}, {"model_class": "TextToolParameter", "name": "custom_tag", "argument": null, "type": "text", "label": "use this custom tag to store consequences rather than the default BCSQ tag", "help": "", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": [], "default_value": "", "text_value": "Empty."}]}, {"model_class": "Section", "name": "sec_restrict", "type": "section", "title": "Restrict to", "help": null, "expanded": false, "inputs": [{"model_class": "Conditional", "name": "regions", "type": "conditional", "cases": [{"model_class": "ConditionalWhen", "value": "__none__", "inputs": []}, {"model_class": "ConditionalWhen", "value": "regions", "inputs": [{"model_class": "Repeat", "name": "regions", "type": "repeat", "title": "Region Filter", "help": null, "default": 1, "min": 1, "max": "__Infinity__", "inputs": [{"model_class": "TextToolParameter", "name": "chrom", "argument": null, "type": "text", "label": "Region chromosome", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "start", "argument": null, "type": "text", "label": "Region start position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "stop", "argument": null, "type": "text", "label": "Region end position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}], "cache": {}}]}, {"model_class": "ConditionalWhen", "value": "regions_file", "inputs": [{"model_class": "DataToolParameter", "name": "regions_file", "argument": null, "type": "data", "label": "Regions File", "help": "restrict to Regions listed in a file", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "extensions": ["tabular"], "edam": {"edam_formats": ["format_3475"], "edam_data": ["data_0006"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "955b0e088867ea92", "hid": 10, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta (as tabular)", "tags": [], "src": "hda", "keep": false}, {"id": "3ba2ccc043967969", "hid": 3, "name": "Extract MAF blocks on data 2 (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "57c61e66a8a42935", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "1d6404f66ed3d72e", "hid": 1, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "text_value": "No dataset."}]}], "test_param": {"model_class": "SelectToolParameter", "name": "regions_src", "argument": null, "type": "select", "label": "Regions", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": "__none__", "options": [["Do not restrict to Regions", "__none__", false], ["Specify one or more Region(s) directly", "regions", false], ["Operate on Regions specified in a history dataset", "regions_file", false]], "display": null, "multiple": false, "textable": false, "text_value": "Do not restrict to Regions"}}, {"model_class": "Conditional", "name": "targets", "type": "conditional", "cases": [{"model_class": "ConditionalWhen", "value": "__none__", "inputs": []}, {"model_class": "ConditionalWhen", "value": "targets", "inputs": [{"model_class": "Repeat", "name": "targets", "type": "repeat", "title": "Target Filter", "help": null, "default": 1, "min": 1, "max": "__Infinity__", "inputs": [{"model_class": "TextToolParameter", "name": "chrom", "argument": null, "type": "text", "label": "Target chromosome", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "start", "argument": null, "type": "text", "label": "Target start position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "stop", "argument": null, "type": "text", "label": "Target end position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}], "cache": {}}]}, {"model_class": "ConditionalWhen", "value": "targets_file", "inputs": [{"model_class": "DataToolParameter", "name": "targets_file", "argument": null, "type": "data", "label": "Targets File", "help": "restrict to Targets listed in a file", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "extensions": ["tabular"], "edam": {"edam_formats": ["format_3475"], "edam_data": ["data_0006"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "955b0e088867ea92", "hid": 10, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta (as tabular)", "tags": [], "src": "hda", "keep": false}, {"id": "3ba2ccc043967969", "hid": 3, "name": "Extract MAF blocks on data 2 (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "57c61e66a8a42935", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "1d6404f66ed3d72e", "hid": 1, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "text_value": "No dataset."}]}], "test_param": {"model_class": "SelectToolParameter", "name": "targets_src", "argument": null, "type": "select", "label": "Targets", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": "__none__", "options": [["Do not restrict to Targets", "__none__", false], ["Specify one or more Target(s) directly", "targets", false], ["Operate on Targets specified in a history dataset", "targets_file", false]], "display": null, "multiple": false, "textable": false, "text_value": "Do not restrict to Targets"}}, {"model_class": "TextToolParameter", "name": "include", "argument": "--include", "type": "text", "label": "Include", "help": "Select sites for which the expression is true", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "area": false, "datalist": [], "default_value": null, "text_value": "Not available."}, {"model_class": "TextToolParameter", "name": "exclude", "argument": "--exclude", "type": "text", "label": "Exclude", "help": "Exclude sites for which the expression is true", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "area": false, "datalist": [], "default_value": null, "text_value": "Not available."}]}, {"model_class": "Section", "name": "sec_subset", "type": "section", "title": "Subset Options", "help": null, "expanded": false, "inputs": [{"model_class": "TextToolParameter", "name": "samples", "argument": "--samples", "type": "text", "label": "Samples", "help": "Comma separated list of samples to annotate (or exclude)", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": [], "default_value": "", "text_value": "Empty."}, {"model_class": "BooleanToolParameter", "name": "invert_samples", "argument": null, "type": "boolean", "label": "Invert Samples", "help": "Inverts the query/filtering applied by Samples (adds \\"^\\" prefix to exclude)", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "false", "truevalue": "^", "falsevalue": "", "default_value": "false", "text_value": "false"}, {"model_class": "DataToolParameter", "name": "samples_file", "argument": "--samples_file", "type": "data", "label": "Samples file", "help": "File of samples to include", "refresh_on_change": true, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "extensions": ["tabular"], "edam": {"edam_formats": ["format_3475"], "edam_data": ["data_0006"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "955b0e088867ea92", "hid": 10, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta (as tabular)", "tags": [], "src": "hda", "keep": false}, {"id": "3ba2ccc043967969", "hid": 3, "name": "Extract MAF blocks on data 2 (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "57c61e66a8a42935", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "1d6404f66ed3d72e", "hid": 1, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": null, "text_value": "No dataset."}, {"model_class": "BooleanToolParameter", "name": "invert_samples_file", "argument": null, "type": "boolean", "label": "Invert Samples file", "help": "inverts the query/filtering applied by Samples file", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "false", "truevalue": "^", "falsevalue": "", "default_value": "false", "text_value": "false"}]}, {"model_class": "SelectToolParameter", "name": "output_type", "argument": null, "type": "select", "label": "", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "b", "options": [["compressed BCF", "b", false], ["uncompressed VCF", "v", false]], "display": null, "multiple": false, "textable": false, "default_value": "b", "text_value": "compressed BCF"}]
I am trying to convert this dynamic string to an object using
JSON.parse(Kernel_inputs_as_string)
It works perfectly for all the cases except a few in which string contains "^" char. It throws an error.
SyntaxError: Unexpected token ^ in JSON at position 13477 error
On the other hand, when I copy and save the console.log string as input and trying JSON.parse() it work perfectly as described below.
const json = '[{"model_class": "DataToolParameter", "name": "input_file".....}]'
const obj = JSON.parse(json);
console.log(obj[0]);
I'm not able to understand why this error is coming and how to solve it for similar cases where the string has "^" char.
Please help me to solve this error.
Thank you

JS Merging object properties from an array of objects by matching ids

I have two arrays of objects. I want to look at the first one, find typeId then look in the second array for the match (states.typeId == stateTypes.id) then merge those properties into the first array's found match object. If the properties have same key append "stateType" to the property name if not just bring it over. I think an example would best explain it.
Array of objects
"states": [
{
"id": 1,
"typeId": 1,
"name": "CREATED",
"description": "Created",
"label": "Created",
"perviousNotMatchKey": "Text"
},
{
"id": 2,
"typeId": 3,
"name": "ASSIGNED",
"description": "Assigned",
"label": "Assigned",
"perviousNotMatchKey": "Text"
},
{
"id": 3,
"typeId": 3,
"name": "COMPLETED",
"description": "Completed",
"label": "Completed",
"perviousNotMatchKey": "Text"
}
],
"stateTypes": [
{
"id": 1,
"name": "PENDING",
"description": "Pending",
"label": "Pending",
"newIncomingKey": "Text"
},
{
"id": 2,
"name": "IN_PROGRESS",
"description": "In Progress",
"label": "In Progress",
"newIncomingKey": "Text"
},
{
"id": 3,
"name": "COMPLETED",
"description": "Completed",
"label": "Completed",
"newIncomingKey": "Text"
}
],
Wanted array
"newArray": [
{
"id": 1,
"typeId": 1,
"name": "CREATED",
"description": "Created",
"label": "Created",
"perviousNotMatchKey": "Text",
"newIncomingKey": "Text",
"stageType-id": 1,
"stageType-name": "PENDING",
"stageType-description": "Pending",
"stageType-label": "Pending"
},
{
"id": 2,
"typeId": 3,
"name": "ASSIGNED",
"description": "Assigned",
"label": "Assigned",
"perviousNotMatchKey": "Text",
"newIncomingKey": "Text",
"stageType-id": 3,
"stageType-name": "COMPLETED",
"stageType-description": "Completed",
"stageType-label": "Completed"
},
{
"id": 3,
"typeId": 2,
"name": "COMPLETED",
"description": "Completed",
"label": "Completed",
"perviousNotMatchKey": "Text",
"newIncomingKey": "Text",
"stageType-id": 2,
"stageType-name": "IN_PROGRESS",
"stageType-description": "In Progress",
"stageType-label": "In Progress"
}
],
Something like this:
const state = [
{
"id": 1,
"typeId": 1,
"name": "CREATED",
"description": "Created",
"label": "Created",
"perviousNotMatchKey": "Text"
},
{
"id": 2,
"typeId": 3,
"name": "ASSIGNED",
"description": "Assigned",
"label": "Assigned",
"perviousNotMatchKey": "Text"
},
{
"id": 3,
"typeId": 3,
"name": "COMPLETED",
"description": "Completed",
"label": "Completed",
"perviousNotMatchKey": "Text"
}
];
const stateTypes = [
{
"id": 1,
"name": "PENDING",
"description": "Pending",
"label": "Pending",
"newIncomingKey": "Text"
},
{
"id": 2,
"name": "IN_PROGRESS",
"description": "In Progress",
"label": "In Progress",
"newIncomingKey": "Text"
},
{
"id": 3,
"name": "COMPLETED",
"description": "Completed",
"label": "Completed",
"newIncomingKey": "Text"
}
];
const temp = {};
for (const obj1 of state) {
temp[obj1.id] = { ...obj1 };
}
for (const obj2 of stateTypes) {
const destination = temp[obj2.id];
for (const [key, value] of Object.entries(obj2)) {
if (destination[key]) destination[`stateTypes-${key}`] = value;
else destination[key] = value;
}
}
const newArray = Object.values(temp);
console.log(newArray);

Get the distinct object from the array of objects in Typescript Angular 8

I have an array of object as shown below:
[{
"name": "Okta Verify Push",
"provider": "OKTA",
"type": "push",
"status": 0,
"id": "opfhgfgaidhyBw2H90h7"
}, {
"name": "Okta Verify TOTP",
"provider": "OKTA",
"type": "token:software:totp",
"status": 0,
"id": "osthgek5jmWTckcka0h7"
}, {
"name": "Unknown",
"provider": "CUSTOM",
"type": "claims_provider",
"status": 1,
"id": "clpn4wdtqtH6geILD0h7"
}, {
"name": "Google Authenticator",
"provider": "GOOGLE",
"type": "token:software:totp",
"status": 1,
"id": null
}]
I want to get the distinct object as array based on the **provider**
I tried
[...new Set(item.filter(factor => factor.status == MultiFactorAuthenticationEnrolmentStatus.Enrolled).map(factor => factor.provider))];
This returns string of array such as ["GOOGLE", "OKTA","CUSTOM"]
My requirement is to get the Array of Object such as
[{
"name": "Okta Verify Push",
"provider": "OKTA",
"type": "push",
"status": 0,
"id": "opfhgfgaidhyBw2H90h7"
}, {
"name": "Unknown",
"provider": "CUSTOM",
"type": "claims_provider",
"status": 1,
"id": "clpn4wdtqtH6geILD0h7"
}, {
"name": "Google Authenticator",
"provider": "GOOGLE",
"type": "token:software:totp",
"status": 1,
"id": null
}]
Reference - How to get distinct values from an array of objects in JavaScript?
In the case that you have a preference for taking the first occurrence, you can first map the data into an object based on provider being the key and itself as the value. Once that is done, you can then extract the all of the values with Object#values.
const data = [{
"name": "Okta Verify Push",
"provider": "OKTA",
"type": "push",
"status": 0,
"id": "opfhgfgaidhyBw2H90h7"
}, {
"name": "Okta Verify TOTP",
"provider": "OKTA",
"type": "token:software:totp",
"status": 0,
"id": "osthgek5jmWTckcka0h7"
}, {
"name": "Unknown",
"provider": "CUSTOM",
"type": "claims_provider",
"status": 1,
"id": "clpn4wdtqtH6geILD0h7"
}, {
"name": "Google Authenticator",
"provider": "GOOGLE",
"type": "token:software:totp",
"status": 1,
"id": null
}]
const values = Object.values(
data.reduce((a, b) => {
if (!a[b.provider]) a[b.provider] = b
return a
}, {})
)
console.log(values)

Find multiple elements in nested array

I Need to find multiple elements in a nested array and return it as an array.
I use the reduce function to find the elements, but it returns only one record.
Nested array:
{
"type": "group",
"level": 0,
"expand": "-closed",
"selected": false,
"text": "Федулов Владислав Владиславович",
"phoneNumber": "+7 (927) 999 9999",
"email": "qweeqwe#mail.ru",
"id": 24,
"parent": null,
"cardType": 0,
"childrens": [
{
"type": "group",
"level": 1,
"expand": "-closed",
"selected": false,
"text": "Ширяев Феликс Богуславович",
"phoneNumber": "+7 (123) 456 7810",
"email": "test#test.ru",
"id": 47,
"parent": 24,
"cardType": 0,
"childrens": [
{
"type": "manager",
"level": 2,
"expand": "-empty",
"selected": false,
"text": "Колесова Анастасия Олеговна",
"phoneNumber": "+7 (900) 000 0001",
"email": "eprosvirina#baccasoft.ru",
"id": 58,
"parent": 47,
"cardType": 0,
"childrens": null
}
]
}
]
},
{
"type": "group",
"level": 0,
"expand": "-closed",
"selected": false,
"text": "Игнатьева Женевьева Павловна",
"phoneNumber": "+7 (777) 777 7777",
"email": "igp#sks.ru",
"id": 3,
"parent": null,
"cardType": 0,
"childrens": [
{
"type": "group",
"level": 1,
"expand": "-closed",
"selected": false,
"text": "Меретин Викентий Васильевич",
"phoneNumber": "+7 (917) 193 5222",
"email": "keshman#gmail.com",
"id": 2,
"parent": 3,
"cardType": 1,
"childrens": [
{
"type": "manager",
"level": 2,
"expand": "-empty",
"selected": false,
"text": "Климаков Алексей Александрович",
"phoneNumber": "+7 (903) 888 8888",
"email": "krenog#gmail.com",
"id": 20,
"parent": 2,
"cardType": 1,
"childrens": null
}
]
}
]
}
and the reduce function:
var array = store.managersTree.treeNodes;
var items = [];
const findItemNested = (arr, searchString, nestingKey) => (
arr.reduce((a, item) => {
if (a) return a;
if (item.text.indexOf(searchString)!==-1 ||
item.phoneNumber.indexOf(searchString)!==-1 ||
item.email.indexOf(searchString)!==-1) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey],
searchString, nestingKey)
}, [])
);
const element = findItemNested(array, searchString, "childrens");
I am trying to find a record matching at least one criteria, expecting that reduce returns multiple records, but this returns only one record, despite there were multiple records found.
Any help would be appreciated.
UPD: searchString could be string like phoneNumber, text or email
You could reduce the array recursively.
Destructure the object in reduce parameter to get nestingKey and other properties separately
Create an array of filterKeys which have the keys which you want to search for searchString.
Use some to check if any of the fields in the object have a value which includes the searchString.
If nestingKey exists, you can push the nested items to the accumulator array.
const input=[{"type":"group","level":0,"expand":"-closed","selected":false,"text":"Федулов Владислав Владиславович","phoneNumber":"+7 (927) 999 9999","email":"qweeqwe#mail.ru","id":24,"parent":null,"cardType":0,"childrens":[{"type":"group","level":1,"expand":"-closed","selected":false,"text":"Ширяев Феликс Богуславович","phoneNumber":"+7 (123) 456 7810","email":"test#test.ru","id":47,"parent":24,"cardType":0,"childrens":[{"type":"manager","level":2,"expand":"-empty","selected":false,"text":"Колесова Анастасия Олеговна","phoneNumber":"+7 (900) 000 0001","email":"eprosvirina#baccasoft.ru","id":58,"parent":47,"cardType":0,"childrens":null}]}]},{"type":"group","level":0,"expand":"-closed","selected":false,"text":"Игнатьева Женевьева Павловна","phoneNumber":"+7 (777) 777 7777","email":"igp#sks.ru","id":3,"parent":null,"cardType":0,"childrens":[{"type":"group","level":1,"expand":"-closed","selected":false,"text":"Меретин Викентий Васильевич","phoneNumber":"+7 (917) 193 5222","email":"keshman#gmail.com","id":2,"parent":3,"cardType":1,"childrens":[{"type":"manager","level":2,"expand":"-empty","selected":false,"text":"Климаков Алексей Александрович","phoneNumber":"+7 (903) 888 8888","email":"krenog#gmail.com","id":20,"parent":2,"cardType":1,"childrens":null}]}]}],
filterKeys = ["text", "phoneNumber", "email"];
function findItemNested(array, searchString, nestingKey) {
return array.reduce((acc, { [nestingKey]: nested, ...o }) => {
if (filterKeys.some(k => o[k] && o[k].includes(searchString)))
acc.push(o)
if (nested)
acc.push(...findItemNested(nested, searchString, nestingKey))
return acc;
}, [])
}
console.log(findItemNested(input, "keshman", "childrens"))
console.log(findItemNested(input, "#gmail.com", "childrens"))
Always Array.reduce returns a single value after processing each element in the array. If you want to return matching records in array then you can use, Array.filter,
[1,2,3,4,5].filter((element) => {
return (element === 2 || element ===4);
});
For this above code, the filtered array will be,
[2,4]
And before filter you should either flat the array or should traverse each and every element to filter the array instead of using Array.filter()
Without reduce also its possible,
var s = [{
"type": "group",
"level": 0,
"expand": "-closed",
"selected": false,
"text": "Федулов Владислав Владиславович",
"phoneNumber": "+7 (927) 999 9999",
"email": "qweeqwe#mail.ru",
"id": 24,
"parent": null,
"cardType": 0,
"childrens": [
{
"type": "group",
"level": 1,
"expand": "-closed",
"selected": false,
"text": "Ширяев Феликс Богуславович",
"phoneNumber": "+7 (123) 456 7810",
"email": "test#test.ru",
"id": 47,
"parent": 24,
"cardType": 0,
"childrens": [
{
"type": "manager",
"level": 2,
"expand": "-empty",
"selected": false,
"text": "Колесова Анастасия Олеговна",
"phoneNumber": "+7 (900) 000 0001",
"email": "eprosvirina#baccasoft.ru",
"id": 58,
"parent": 47,
"cardType": 0,
"childrens": null
},
{
"type": "group",
"level": 2,
"expand": "-empty",
"selected": false,
"text": "Колесова Анастасия Олеговна",
"phoneNumber": "+7 (900) 000 0001",
"email": "eprosvirina#baccasoft.ru",
"id": 534,
"parent": 47,
"cardType": 0,
"childrens": null
},
{
"type": "manager",
"level": 2,
"expand": "-empty",
"selected": false,
"text": "Колесова Анастасия Олеговна",
"phoneNumber": "+7 (900) 000 0001",
"email": "eprosvirina#baccasoft.ru",
"id": 523,
"parent": 47,
"cardType": 0,
"childrens": null
}
]
}
]
},
{
"type": "manager",
"level": 0,
"expand": "-closed",
"selected": false,
"text": "Игнатьева Женевьева Павловна",
"phoneNumber": "+7 (777) 777 7777",
"email": "igp#sks.ru",
"id": 3,
"parent": null,
"cardType": 0,
"childrens": [
{
"type": "group",
"level": 1,
"expand": "-closed",
"selected": false,
"text": "Меретин Викентий Васильевич",
"phoneNumber": "+7 (917) 193 5222",
"email": "keshman#gmail.com",
"id": 2,
"parent": 3,
"cardType": 1,
"childrens": [
{
"type": "manager",
"level": 2,
"expand": "-empty",
"selected": false,
"text": "Климаков Алексей Александрович",
"phoneNumber": "+7 (903) 888 8888",
"email": "krenog#gmail.com",
"id": 20,
"parent": 2,
"cardType": 1,
"childrens": null
}
]
}
]
}];
function filterRequiredElement(arr, searchString, nestingKey) {
arr.forEach((item, index) => {
if (item.type !== searchString || item.phoneNumber !== searchString || item.email !== searchString) {
arr.splice(index, 1);
}
});
for(let item of arr) {
if (item[nestingKey] !== null) {
filterRequiredElement(item[nestingKey], searchString, nestingKey);
}
}
}
filterRequiredElement(s ,'Климаков Алексей Александрович', 'childrens');
console.log(s);

Categories

Resources