Need to group data in Object based on value - javascript

I am using React/Typescript in my application but need help with basic JavaScript. I am trying to group the data coming from an api call (in this example i'll use mock data) without modifying the actual JSON. I need to group the data based on the 'deviceType' value. So if there are 4 objects, if two are ipad and two are iphone, I need to group those in order. Right now, the mock data is showing Ipad air, then Iphone 6plus, then Ipad air, and then Iphone 6plus again. I need to group these so the new object has the two ipadAir objects first and then the iphone 6plus object coming after. I believe this can be done by making a copy of the old object using spread operator and then modifying it before returning. Here is the data object:
{
"data": {
"DirectvNowDeviceNotifications": [
{
"AccountNumber": "180802190357553",
"AlertDescription": [
{
"AlertType": "BUFFERINGERRORS",
"AlertCode": "CRITICAL_ISFATAL",
"AlertInfo": "ACCOUNT_ALERT",
"SkipDismissal": false,
"DISMISSAL_EXPIRY_DATE": "",
"Content": {
"issueTitle": "Buffering Error Detected",
"issueDescription": "Buffering Error Detected"
},
"AlertAdditionalInfo": [
{
"Name": "reasonCodes",
"Value": "CRITICAL_ISFATAL"
},
{
"Name": "make",
"Value": "APPLE"
},
{
"Name": "deviceType",
"Value": "IPAD AIR"
},
{
"Name": "deviceID",
"Value": "F920BE29-1321-498A-B5D7-7FA84396DE16"
},
{
"Name": "osName",
"Value": "IOS"
},
{
"Name": "ISP",
"Value": "TIME WARNER CABLE INTERNET LLC"
},
{
"Name": "Mobile Carrier",
"Value": "AT&T"
},
{
"Name":"workflowName",
"Value":"CCE_ATTTV_Wifi_Setup"
}
],
"AdditionalContent": {
"longDescription": "You received this error message because the system has captured buffering errors on your device while streaming."
}
},
{
"AlertType": "BUFFERINGERRORS",
"AlertCode": "CRITICAL_FATALV",
"AlertInfo": "ACCOUNT_ALERT",
"SkipDismissal": false,
"DISMISSAL_EXPIRY_DATE": "",
"Content": {
"issueTitle": "Buffering Error Detected",
"issueDescription": "Buffering Error Detected"
},
"AlertAdditionalInfo": [
{
"Name": "reasonCodes",
"Value": "CRITICAL_FATALVIDEOERROR_CT"
},
{
"Name": "make",
"Value": "APPLE"
},
{
"Name": "deviceType",
"Value": "IPHONE 6 PLUS"
},
{
"Name": "deviceID",
"Value": "F920BE29-1321-498A-B5D7-7FA84396DE16"
},
{
"Name": "osName",
"Value": "IOS"
},
{
"Name": "ISP",
"Value": "TIME WARNER CABLE INTERNET LLC"
},
{
"Name": "Mobile Carrier",
"Value": "AT&T"
},
{
"Name":"workflowName",
"Value":"CCE_DTVN_PLAYER_ERRORS"
},
{
"Name":"workflowName",
"Value":"CCE_DTVN_PLAYER_ERRORS"
}
],
"AdditionalContent": {
"longDescription": "You received this error message because the system has captured buffering errors on your device while streaming"
}
},
{
"AlertType": "OSUNSUPPORTED",
"AlertCode": "N_NOT_SUPPORTED",
"AlertInfo": "ACCOUNT_ALERT",
"SkipDismissal": false,
"DISMISSAL_EXPIRY_DATE": "",
"Content": {
"issueTitle": "The device you are trying to use with DIRECTV NOW is not supported.",
"issueDescription": "The device you are trying to use with DIRECTV NOW is not supported."
},
"AlertAdditionalInfo": [
{
"Name": "reasonCodes",
"Value": "VSTB_UNSUPPORTED_DEVICE"
},
{
"Name": "make",
"Value": "APPLE"
},
{
"Name": "deviceType",
"Value": "IPAD AIR"
},
{
"Name": "deviceID",
"Value": "F920BE29-1321-498A-B5D7-7FA84396DE16"
},
{
"Name": "osName",
"Value": "IOS"
},
{
"Name": "ISP",
"Value": "TIME WARNER CABLE INTERNET LLC"
},
{
"Name": "Mobile Carrier",
"Value": "AT&T"
},
{
"Name":"workflowName",
"Value":"CCE_DTVN_PLAYER_ERRORS"
}
],
"AdditionalContent": {
"longDescription": "<a target='_blank' href='https://www.att.com/esupport/article.html#!/directv-now/KM1200941'>Here</a> is a list of supported devices."
}
},
{
"AlertType": "NA",
"AlertCode": "NA",
"AlertInfo": "NA",
"SkipDismissal": false,
"DISMISSAL_EXPIRY_DATE": "",
"Content": {
"issueTitle": "tell me more title",
"issueDescription": "tell me more description"
},
"AlertAdditionalInfo": [
{
"Name": "reasonCodes",
"Value": "NA"
},
{
"Name": "make",
"Value": "APPLE"
},
{
"Name": "deviceType",
"Value": "IPHONE 6 PLUS"
},
{
"Name": "deviceID",
"Value": "FB2468CF-BF73-4DBC-9600-C61553BB759F"
},
{
"Name": "osName",
"Value": "IOS"
},
{
"Name": "ISP",
"Value": "TIME WARNER CABLE INTERNET LLC"
},
{
"Name": "Mobile Carrier",
"Value": "AT&T"
}
],
"AdditionalContent": {
"longDescription": "tell me more long long long description"
}
}
]
}
]
},
"content": {
"code": 200,
"message": "OK"
}
}
Need objects to be grouped based on device type and return a new object with the proper grouping. Please if anyone can help I would greatly appreciate it, I have been struggling with this. Thank you

You could go through the keys of your object, in the following example I assume that you define this as a javascript object, the result will be two objects each with a key corresponding to the type of device
const newGroup = [];
const data = object["data"]["DirectvNowDeviceNotifications"];
(data).forEach((map, index) => {
Object(map['AlertDescription']).forEach((devices) => {
if(typeof devices['AlertAdditionalInfo'] !== 'undefined'){
const deviceType = devices['AlertAdditionalInfo'].find((type) => type.Name ==='deviceType');
if(typeof deviceType.Value !== 'undefined'){
if(typeof newGroup[deviceType.Value] === 'undefined'){
newGroup[deviceType.Value] = [];
}
newGroup[deviceType.Value].push(devices);
}
}
})
});
example working
this code is just an example you should optimize, the idea is to give you an idea of ​​solution

Related

Creating new json by taking url addresses from existing json and split it up Javascript

I have a json file.
[
{
"line": 1,
"elements": [
{
"start_timestamp": "2022-10-17T20:07:41.706Z",
"steps": [
{
"result": {
"duration": 12216552000,
"status": "passed"
},
"line": 5,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
},
{
"result": {
"duration": 2074982200,
"status": "passed"
},
"line": 6,
"name": "m1e1",
"match": {
"location": "seleniumgluecode.book.user_enters_Usernamee()"
},
"keyword": "When "
}
],
"tags": [
{
"name": "#Smokee"
}
]
},
{
"start_timestamp": "2022-10-17T20:08:12.284Z",
"steps": [
{
"result": {
"duration": 12090584100,
"status": "passed"
},
"line": 12,
"name": "m0e2",
"match": {
"location": "seleniumgluecode.book2.user_is_on_homepageee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "Login Featuree",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featuree",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe/squad1/kitab.feature",
"tags": []
},
{
"line": 1,
"elements": [
{
"start_timestamp": "2022-10-17T20:08:34.480Z",
"steps": [
{
"result": {
"duration": 11366098500,
"status": "passed"
},
"line": 5,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "Login Featureefghfgh",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featureefghfgh",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature",
"tags": []
},
{
"line": 19,
"elements": [
{
"start_timestamp": "2022-10-17T20:09:40.836Z",
"steps": [
{
"result": {
"duration": 12761711100,
"status": "passed"
},
"line": 23,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "X Feature",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featuree",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe2/test.feature",
"tags": []
}
]
I am getting url addresses in this array
document.addEventListener("DOMContentLoaded", () => {
var i = report.length;
var array = [];
for(x = 0; x < i; x++){
array.push(report[x].uri.split("/"));
}
console.log(array2);
});
This return me :
0:
(7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad1', 'kitab.feature']
1:
(7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad2', 'kitab2.feature']
2:
(6) ['file:src', 'test', 'java', 'features', 'tribe2, kitab3.feature']
I don't need file:src, test, java, features. Deleting them in 3 arrays and getting a unique array like this:
0:
(3) ['tribe1', 'squad1', 'kitab.feature']
1:
(3) ['tribe1', 'squad2', 'kitab2.feature']
2:
(2) ['tribe2, kitab3.feature']
Finally, if there are 2 elements before the .feature, I need to create a new array by considering 1 as squad and 2 as tribe. Like this:
Diagram
[tribe1
squad1
elem
1
2
name
url
squad2
elem
1
2
name
url
tribe2
elem
1
2
name
url
]
How can I do that?. Thank you.
You should try destructing the array. An example is shown below:
[a,b,c,d, ...rest] = ['file:src', 'test', 'java', 'features', 'tribe1', 'squad1', 'kitab.feature']
console.log(rest);
You can transform or create a new array based on input array with this simple logic with the help of Array.map() along with String.split() and Array.splice() method.
Live Demo :
const arr = [
{
"line": 1,
"uri": "file:src/test/java/features/tribe/squad1/kitab.feature"
},
{
"line": 1,
"uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature"
},
{
"line": 19,
"uri": "file:src/test/java/features/tribe2/test.feature"
}
];
const res = arr.map(({ uri}) => uri.split('/').splice(4));
console.log(res);

in JavaScript what is the equivalent of python open(filepath, 'rb')

I can open the file in binary mode with Python and store it in a variable.
I have been researching this for two days, and I can't seem to find a straightforward answer. I need this because I have been working on a project that we have completed in Python, but we need to convert it into JavaScript. The issue that I'm having is that I need to send a file through an API call. Still, every time I do, I get this error ' HTTP 415 Unsupported Media TypeThe provided media type is not supported for the requested URI. What I have is a JSON file that I need to pass to a post-call in binary
files = {'file': open(JSON_File, 'rb')}
response = requests.post(
URL,
auth=(USERNAME, PASSWORD),
files=files
#files=files, verify = False
)
response.text
how can I do this in nodeJS? I completed the above already in Python.
Here is what the the files variable prints from the python code.
files = {'file': open(JSON_File_path, 'rb')}
print(files) => {'file': <_io.BufferedReader name='my_json_file.json'>}
Here is and example of what my json file contains:
[
{
"resourceType": "Domain",
"identifier": {
"name": "ZZ_CRM",
"community": {
"name": "Intermediate APIs"
}
},
"type": {
"name": "Data Asset Domain"
}
},
{
"resourceType": "Domain",
"identifier": {
"name": "ZZ_Source to Target Mappings",
"community": {
"name": "Intermediate APIs"
}
},
"type": {
"name": "Mapping Domain"
}
},
{
"resourceType": "Asset",
"identifier": {
"name": "Client Name",
"domain": {
"name": "ZZ_CRM",
"community": {
"name": "Intermediate APIs"
}
}
},
"type": {
"name": "Data Element"
}
},
{
"resourceType": "Asset",
"identifier": {
"name": "Client ID",
"domain": {
"name": "ZZ_CRM",
"community": {
"name": "Intermediate APIs"
}
}
},
"type": {
"name": "Data Element"
}
},
{
"resourceType": "Asset",
"identifier": {
"name": "SQL Server Mapping",
"domain": {
"name": "ZZ_Source to Target Mappings",
"community": {
"name": "Intermediate APIs"
}
}
},
"type": {
"name": "Mapping Specification"
}
},
{
"resourceType": "Complex Relation",
"identifier": {
"relations": {
"00000000-0000-0000-0000-000000007088:TARGET": [
{
"name": "SQL Server Mapping1Name",
"domain": {
"name": "ZZ_Source to Target Mappings1Name",
"community": {
"name": "Intermediate APIs1Name"
}
}
}
],
"00000000-0000-0000-0000-000000007089:TARGET": [
{
"name": "Client ID",
"domain": {
"name": "ZZ_CRM",
"community": {
"name": "Intermediate APIs"
}
}
}
],
"00000000-0000-0000-0000-000000007090:TARGET": [
{
"name": "SQL Server Mapping",
"domain": {
"name": "ZZ_Source to Target Mappings",
"community": {
"name": "Intermediate APIs"
}
}
}
]
}
},
"complexRelationType": {
"name": "Field Mapping"
},
"attributes": {
"Transformation Logic": [
{
"value": "`clientsWithType` AS select `client`.`client_id` AS `id`, concat( concat( `client`.`name`, ' ' ), `client`.`surname` ) AS `fullname`, `client_type`.`value` AS `client_type`, `client`.`email_address` AS `email_address` from ( `client` join `client_type` on (( `client`.`client_type` = `client_type`.`code` )));"
}
]
}
}
]
You could use fs module that's included in nodejs
fs.readFileSync(file_path);

Sort an array of object fetched from db rendered in a Flatlist React native

I have this array of object that i want to sort when i display them on my screen, sort them by type.here is a look of the array:
Array [
Object {
"lien": "get_praticien",
"name": "tag service centre 2",
"type": "Tag",
},
Object {
"lien": "get_praticien",
"name": "Ambulance",
"type": "Acte",
},
Object {
"lien": "get_praticien",
"name": "Réadaptation Fonctionnelle",
"type": "speciality",
},
Object {
"lien": "get_praticien",
"name": "Infirmité Motrice",
"type": "Tag",
},......
so i want the objects that have a type:"speciality" to be at the top of the flatlist, and the others after on whatever order.
i'm using a flatlist :
<FlatList
data={this.state.dataSource}
keyExtractor={item=> { return item.id.toString()}}
renderItem= {({item})=> <MedItem Med={item} />} />
i'll appreciate you answers
use a sort function to sort your data list before rendering. Also you may want to sort them on server side if you have multiple pages of data.
const test = [
{
"lien": "get_praticien",
"name": "tag service centre 2",
"type": "Tag",
},
{
"lien": "get_praticien",
"name": "Ambulance",
"type": "Acte",
},
{
"lien": "get_praticien",
"name": "Réadaptation Fonctionnelle",
"type": "speciality",
},
{
"lien": "get_praticien",
"name": "Infirmité Motrice",
"type": "Tag",
},
{
"lien": "get_praticien",
"name": "Infirmité Motrice",
"type": "speciality",
},
{
"lien": "get_praticien",
"name": "Ambulance",
"type": "Acte",
},
{
"lien": "test",
"name": "test Motrice",
"type": "speciality",
},
]
console.log(test.sort((a,b) => a.type === 'speciality' ? -1 : 1))

What is the best way to replace text in json?

So I have a bunch of JSON data and it contains a few fields. for example:
[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
what I'm trying to do is kind of conversion table (from a different JSON file)
if a field has the value 'a' replace it with 'some other text..' etc.
I have a service for the JSON pipeline, so I guess this is the right place to do the replacement.
so for this example, I have the JSON above and in my conversion table I have the following terms:
next: forward,
song: music,
a: option1,
just: from
etc...
What you are looking for can be achieved with templates. Replace the variable sections with some specific markers that you can find and replace from some external tools such as perl or sed.
For example, you could have a template.json with something like this:
...
"type": {
"value": "##VALUE##"
}
...
Then when you need the actual JSON, you could pass this though an intermediate script that replaces these templates with actual data.
cat template.json | sed -e 's/##VALUE##/my_value/' > target.json
Alternatively, with Perl:
cat template.json | perl -pi -e 's:\#\#VALUE\#\#:my_value:' > target.json
The best way is to parse it, replace the text in the object, and then stringify it.
The next best way is to use a regular expression.
In this example, I catch exceptions if path cannot be indexed, and use ['type'] instead of .type so it will scale to indexing 'non-type' if you wish.
const data = `[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
`
const o = JSON.parse(data)
o[0].body.forEach(b => {
try {
if (b.extended.spl['type'].value === 'a') {
b.extended.spl['type'].value = 'CHANGED'
}
} catch (e) {}
})
const newData = JSON.stringify(o, null, 2)
console.log(newData)
A string replace approach will work if you know and can rely on your source conforming, such as the only "value" is inside "type"
const data = `[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
`
const newData = data.replace(/"value": "a"/g, '"value": "NEWVALUE"')
console.log(newData)

Convert a model in given json format

I have a model in which values are stored in following format:--
Language-count=3
[0]
-ID="1"
-Name="French"
[1]
-ID="2"
-Name="English"
[2]
-ID="3"
-Name="Hindi"
Titles-count=2
[0]
-ID="1"
-Name="Video1"
[1]
-ID="2"
-Name="Video2"
Countries-count=2
[0]
-ID="1"
-Name="India"
[1]
-ID="2"
-Name="USA"
and I have to convert this model in given json format:-
var models = [
{
name: 'Language',
values: [
'English',
'French',
'Hindi'
]
},
{
name: 'Title',
values: [
'Title 1',
'Title 2'
]
},
{
name: 'Countries',
values: [
'India',
'UK'
]
}
];
In above json format I have hard coded those values of Languages,countries and Titles but I have to fetch it from the above model which I have already given.
The json Format which I am getting is following:--
{
"ID": 1,
"DealID": 1,
"Title": "Position1",
"Titles": [
{
"Icon": "hdtv",
"Name": "\nWedding Bells & Farewells\n",
"ID": 12
},
{
"Icon": "hdtv",
"Name": "Delta Farce",
"ID": 5
},
{
"Icon": "hdtv",
"Name": "Doe B: Let Me Find",
"ID": 9
}
],
"Episodes": [
{
"Icon": "episode",
"Name": "Sparkle",
"ID": 4
},
{
"Icon": "episode",
"Name": "Sparks Fly Out",
"ID": 2
},
{
"Icon": "episode",
"Name": "Uploads by Filmi Gaane",
"ID": 7
}
],
"Assets": [
{
"Icon": "file-o",
"Name": "Best of Javed Akhtar - Jukebox 2 - Javed Akhtar Top 10 Hit Songs",
"ID": 10
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party additional image 1",
"ID": 4
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party box cover",
"ID": 3
}
],
"Documents": [],
"Languages": [
{
"Icon": "globe",
"Name": "Albanian",
"ID": 70
},
{
"Icon": "globe",
"Name": "Amharic",
"ID": 96
}
],
"Territories": [],
"Countries": [
{
"Icon": "globe",
"Name": "Afghanistan",
"ID": 2
},
{
"Icon": "globe",
"Name": "Albania",
"ID": 3
},
{
"Icon": "globe",
"Name": "Algeria",
"ID": 4
}
],
"Rights": [
{
"Icon": "leaf",
"Name": "Ancillary",
"ID": 23
},
{
"Icon": "leaf",
"Name": "Finshed Episode Rights",
"ID": 20
},
{
"Icon": "leaf",
"Name": "Format Group - DO NOT USE",
"ID": 63
}
],
"Contributors": [],
"Transmissions": [],
"Available": null
}
It would be best to write a simple parser and transform your data type to JSON - which would additionally allow you to reuse the parser in the future, and convert it to other data types easily for instance.
You could look at the various YAML parsers for inspiration, which would use a similiar technique for your data set's language.
Alternatively you can create a 'hack' and just keep splitting things up if your data format is always of this format, and doesn't allow arbitrary value nesting.
List personel = new List();
var client = new RestClient("your adres");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "2893de4a-457e-46a7e8efb025");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("token", "a23a80f7-3323-4594056");
IRestResponse response = client.Execute(request);
JObject deger = JObject.Parse(response.Content);
var toplam = deger["data"]["data"].Count();
string jenp = toplam.ToString();
for (int i = 0; i < toplam; i++)
{
Personeller data = new Personeller();
data.Adi = deger["data"]["data"][i]["adi"].ToString();
data.Soyadi = deger["data"]["data"][i]["soyadi"].ToString();
data.tckimlikno = (long)deger["data"]["data"][i]["tckimlikno"];
personel.Add(data);
}

Categories