Lodash - Transform Object to Array and add new key - javascript

I have a firebase database object as below and I need to convert main object value to id key and if savedProject > formatedObjects is present, add additional key called savedLayout and copy that savedProject > formatedObjects to savedLayout key:
{
"-NH0FZXNPnxxPjJGOcUu": {
"name": "Layout_220",
"propLayoutImg": "",
"proposal": "",
"purchaseOrder": "",
"savedProject": {
"canvasInfo": {
"globalShadowToggle": true
},
"formatedObjects": [
{
"cat": "Everything EXCEPT Wire",
"children": [
{
"children": [
{
"sku": "LUM W3B2-3.5W",
"subCat": "Sconce & Wall Lights",
"title": "Lumien Surface Mount Wall Light",
"totalPrice": 279,
"totalPurchasePrice": 78.27,
"type": "group"
}
],
"subCat": "Sconce & Wall Lights"
}
]
}
]
},
"url": "",
"woLayoutImg": "",
"workOrder": ""
},
"-NIreiliC6_LFyBowPnM": {
"name": "Layout_554",
"url": ""
}
}
And I am trying to convert that to array using loadash such that my final output will be:
[
{
id: "-NH0FZXNPnxxPjJGOcUu", //// New Key Value
savedLayout: [ //// New Key Value from Nested Object Array below
{
"cat": "Everything EXCEPT Wire",
"children": [
{
"children": [
{
"sku": "LUM W3B2-3.5W",
"subCat": "Sconce & Wall Lights",
"title": "Lumien Surface Mount Wall Light",
"totalPrice": 279,
"totalPurchasePrice": 78.27,
"type": "group"
}
],
"subCat": "Sconce & Wall Lights"
}
]
}
],
"name": "Layout_220",
"propLayoutImg": "",
"proposal": "",
"purchaseOrder": "",
"savedProject": {
"canvasInfo": {
"globalShadowToggle": true
},
"formatedObjects": [
{
"cat": "Everything EXCEPT Wire",
"children": [
{
"children": [
{
"sku": "LUM W3B2-3.5W",
"subCat": "Sconce & Wall Lights",
"title": "Lumien Surface Mount Wall Light",
"totalPrice": 279,
"totalPurchasePrice": 78.27,
"type": "group"
}
],
"subCat": "Sconce & Wall Lights"
}
]
}
]
},
"url": "",
"woLayoutImg": "",
"workOrder": ""
},
{
id: "-NIreiliC6_LFyBowPnM", //// New Key Value
savedLayout: [ ], //// Empty 'savedLayout' since there is no 'savedProject > formatedObjects'
"name": "Layout_554",
"url": ""
}
]
Any idea how can i add additional keys inside lodash map based on the object ????

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);

How do I sort a GeoJSON features array by a property value?

I am looking to sort a GeoJSON file on a property so I can then slice it keeping only the top 5 features. So for example I wish to take this GeoJSON and sort the file in descending order by the incidents property:
...
[
-75.1972382872565,
39.9294288475177
]
]
]
]
},
"properties": {
"area": "",
"location": "24th St. & Wolf St.",
"perimeter": "81903.64182498",
"dist_numc": "01",
"sum_area": "",
"area_sqmi": "216350124.153",
"district_i": "",
"objectid": "321",
"globalid": "c040618c-ac93-4b22-b174-0ea08e0f805d",
"district_": "1",
"_feature_id": "1",
"_feature_id_string": "Police_Districts.1",
"dist_num": "1",
"div_code": "SPD",
"phone": "686-3010",
"incidents": 11553
}
},
...
I'm looking to basically rearrange the order of the features array so that it's in descending order and the highest incident features are first.
How would I go about this? I am used to creating a compare function and then sorting an array with something like this:
//FUNCTION: SORT
export const compare = ( a, b ) => {
if ( a.incidents < b.incidents ){
return -1;
}
if ( a.incidents > b.incidents ){
return 1;
}
return 0;
}
But in this case I need to sort a JSON and only sort an array inside of it so I am unsure how to proceed.
I set up an example where i attempt to sort via a button click but doesn't seem to be working:
https://codesandbox.io/s/slicing-geojson-qg1hb?file=/src/App.js
Consider this file as JSON. To do that, I've copied the first three data from that geojson file and store into a variable called data. So we need to sort that array according to the incidents property. Now execute javascript's sort() function to data.features. Since your data is big and you're sorting the data according to the incidents property, make sure to print only incidents property to see whether your data is being sorted or not. As StackOverflow asks limited characters(30000) in this section, I'm going to keep only the first three coordinates from every geometry property. Have a look at the snippet below:
var data = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-75.0544420852857,
40.044532749252
],
[
-75.054816199384,
40.0441717116827
],
[
-75.0551367855513,
40.0438732632911
],
]
]
]
},
"properties": {
"area": "",
"location": "Harbison Ave. & Levick St.",
"perimeter": "63587.3693993",
"dist_numc": "02",
"sum_area": "",
"area_sqmi": "192346097.032",
"district_i": "",
"objectid": "322",
"globalid": "95200c4a-2617-47c2-93f1-07d6359a92e9",
"district_": "2",
"_feature_id": "2",
"_feature_id_string": "Police_Districts.2",
"dist_num": "2",
"div_code": "NEPD",
"phone": "686-3020",
"incidents": 32340
}
}
,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-75.1972382872565,
39.9294288475177
],
[
-75.1969248893574,
39.9291749499585
],
[
-75.1966534158686,
39.9293232425744
],
]
]
]
},
"properties": {
"area": "",
"location": "24th St. & Wolf St.",
"perimeter": "81903.64182498",
"dist_numc": "01",
"sum_area": "",
"area_sqmi": "216350124.153",
"district_i": "",
"objectid": "321",
"globalid": "c040618c-ac93-4b22-b174-0ea08e0f805d",
"district_": "1",
"_feature_id": "1",
"_feature_id_string": "Police_Districts.1",
"dist_num": "1",
"div_code": "SPD",
"phone": "686-3010",
"incidents": 11553
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[
[
-75.1343640909741,
39.9529315410666
],
[
-75.1352375679666,
39.9506957263754
],
[
-75.1352409996735,
39.9506869425429
]
]
]
]
},
"properties": {
"area": "",
"location": "11th St. & Winter St.",
"perimeter": "34655.32085552",
"dist_numc": "06",
"sum_area": "",
"area_sqmi": "69279267.8986235",
"district_i": "",
"objectid": "325",
"globalid": "e0afa680-ecd3-470e-b0f8-59b70d4f72b5",
"district_": "6",
"_feature_id": "5",
"_feature_id_string": "Police_Districts.5",
"dist_num": "6",
"div_code": "CPD",
"phone": "686-3060",
"incidents": 23428
}
}
]
};
console.log("Before sorting");
console.log(data.features[0].properties.incidents);
console.log(data.features[1].properties.incidents);
console.log(data.features[2].properties.incidents);
data.features.sort(function (a, b) {
if (a.properties.incidents < b.properties.incidents)
return -1;
else if (a.properties.incidents > b.properties.incidents)
return 1;
});
console.log("After sorting");
console.log(data.features[0].properties.incidents);
console.log(data.features[1].properties.incidents);
console.log(data.features[2].properties.incidents);

Filter method on multidimensional array

I have an id and i to filter a multidimensional array with these. My code is:
service.fakedata.map(f=>{
f.results.map(r=>{
r = r.filter(m=> m.rId !== id)
})
})
and my array is :
"services": [
{
"id": "1839f72e-fa73-47de-b119-49fb971a5730",
"name": "In I/O Route",
"url": "http://wwww.in.io/[param1]/[param2]",
"inputParams": [
{
"id": "e74a6229-4c08-43a1-961f-abeb887fa90e",
"name": "in1",
"datatype": "string"
},
{
"id": "e74a6229-4c08-43a1-961f-abeb887fa90o",
"name": "in2",
"datatype": "string"
}
],
"isArrayResult": false,
"results": [
{
"id": "ef7c98db-9f12-45a8-b3fb-7d09a82abe3d",
"name": "out1",
"datatype": "string",
"fakedatatype": [
"address",
"city"
]
},
{
"id": "9b178ded-af27-43df-920f-daab5ad439b9",
"name": "out2",
"datatype": "string",
"fakedatatype": [
"internet",
"url"
]
}
],
"routeParameters": [
"param1",
"param2"
],
"fakedata": [
{
"id": "b0376694-9612-43d2-93ed-c74264df962e",
"url": "http://wwww.in.io/wood/good",
"params": [
{
"key": "param1",
"value": "wood"
},
{
"key": "param2",
"value": "good"
}
],
"inputParams": [
{
"iId":"e74a6229-4c08-43a1-961f-abeb887fa90e",
"key": "in1",
"value": "m"
},
{
"iId":"e74a6229-4c08-43a1-961f-abeb887fa90o",
"key": "in2",
"value": "z"
}
],
"results": [
{
"rId": "ef7c98db-9f12-45a8-b3fb-7d09a82abe3d",
"key": "out1",
"value": "result1",
"fakedatatype": [
"address",
"city"
]
},
{
"rId": "9b178ded-af27-43df-920f-daab5ad439b9",
"key": "out2",
"value": "result2",
"fakedatatype": [
"internet",
"url"
]
}
]
}
]
}
]
In this case filter is working (when I check with console.log) but it doesn't change fakedata array.
What was wrong with my code?
From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
base on #H77 suggestion i change my code and now my code is look like this and everything work well
const s = service.fakedata.map(f=>{
f.results = f.results.map(r=>{
return r.filter(m=> m.rId !== id)
})
})

Checking a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

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