How to get the dataValueField when I select one node - javascript

I am using kendoTreeView. I want to get the unitId when one node is selected.
This is my code.
$("#treeview").kendoTreeView({
dataSource: dataSource,
dataTextField: "name",
dataValueField: 'unitId'
});
dataSource example:
{
"rows": [{
"_token": "8cfd3e2133d936a6a65c6f7cfb80268a",
"objectVersionNumber": null,
"unitId": 10002,
"parentId": 10001,
"unitCode": "100000",
"name": "Hand",
"description": null,
"managerPosition": null,
"companyId": null,
"enabledFlag": null,
"unitCategory": null,
"unitType": null,
"positionName": null,
"parentName": null,
"parentCode": null,
"hasChildren": true
}],
"success": true,
"total": 1
}

Which method of treeview are you using to capture the click event? You can write a select event that kendoTreeView provides which will give you data of the node you clicked/selected. You can refer this: https://docs.telerik.com/kendo-ui/api/javascript/ui/treeview/events/select
If this doesn't work for you, can you share your DOJO or jsFiddle and I could further help.

Related

Find and replace key in Javascript object

I'm accessing a JSON that comes back looking like this:
[
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"selectionType": "Music",
"sfzFile": "",
"destination": "/data/uploads",
"encoding": "7bit",
"fieldname": "file",
"filename": "782f49a7cd72b865b4e2d286816792e7",
...
"found": true,
"flError": false,
"error_strings": [],
"_id": "5ada2217c114ca048e1db9af",
"created_by": "5ab57289d8d00507b29a3fdd",
"slug": "1105fmid",
"__v": 0,
"createdAt": "2018-04-20T17:23:35.216Z",
"updatedAt": "2018-04-20T17:23:35.788Z",
"selectionTitles": null,
"id": "5ada2217c114ca048e1db9af"
},
"slug": "1105fmid",
"createdAt": "2018-04-20T17:23:35.285Z",
"updatedAt": "2018-04-20T17:23:35.285Z",
"__v": 0,
"id": "5ada2217c114ca048e1db9b0"
}, ...
The react-select node module that I am using takes the key "label" to generate a populated dropdown.
The JSON is coming from the web so I can't control how the JSON is setup. How do I parse the JSON to find all the instances of "name" and replace that key with "label" ?
For example "name" : 1105F.MID" should be changed to "label" : "1105.MID"
Would it be inefficient to convert the entire thing to a string and use the javascript method find/replace?
Assuming your JSON array is stored in the variable data:
data.forEach(item => item.label = item.name)
This would be sufficient to duplicate the name property as the label property for each item in the array.
I have created a function replace() to deal with every object and nested objects, which will add property 'label' if 'name' property is found. Pls see if it's useful to you.
var arr = [
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID"
}
},
{
"itemType": "SelectionTitle",
"name": "test",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "testing"
}
}
]
// this method will take care of adding new property
function replace(obj, from, to) {
Object.entries(obj).forEach(([key, value]) => (
key == from && (obj[to] = obj[from])
, typeof value === "object" && replace(value, from, to)
))
}
arr.forEach(d => replace(d, 'name', 'label'))
// you can check this log for property 'label' whereever 'name' exists
console.log(arr)
Relying on the structure of server response is bad; especially when you say you have not control over it. A better way would be to always parse the server response, construct whatever necessary for the react-select component to work and pass that only.

Assign array of JSON objects to array of interface Angular/Typescript

Currently, this works and doesn't give my error while running but my text editor is giving me an error that says property 'categories' does not exist on type 'CategoryInterface[]' (on the line where response.categories is assigned to variable) so I'm not sure if I'm doing things right.
public categories: CategoryInterface[];
.subscribe((response: CategoryInterface[]) => {
this.categories = response.categories;
console.log(this.categories);
});
My backend returns this:
{
"categories": [
{
"categoryId": 1,
"name": "Important",
"description": "This category is important.",
"order": 1,
"createdBy": null,
"createdAt": "2017-11-25 12:09:04",
"updatedBy": null,
"updatedAt": "2018-01-17 23:53:25",
"categoryBoards": [
{
"categoryBoardId": 1,
"categoryId": 1,
"name": "Announcements",
"description": null,
"order": 2,
"createdBy": null,
"createdAt": "2017-11-25 12:09:49",
"updatedBy": null,
"updatedAt": "2018-01-18 00:09:02"
},
{
"categoryBoardId": 23,
"categoryId": 1,
"name": "Rules",
"description": null,
"order": 1,
"createdBy": null,
"createdAt": "2018-01-18 00:08:57",
"updatedBy": null,
"updatedAt": "2018-01-19 00:05:51"
}
]
}
]
}
You are trying to cast your api response to an array of CategoryInterface which is not the case, you better use your subscribe method like this:
.subscribe((response: any) => {
this.categories = <CategoryInterface[]> response.categories;
console.log(this.categories);
});
It's the your api response categories which needs to be casted to CategoryInterface[]
Bonus: The angular style-guide notice that you need to declare classes instead of interfaces and you don't have to suffix the class name with Interface, so just name your CategoryInterface to Category.
You get the error because you declare response as a CategoryInterface[], but response.categories is actually the CategoryInterface[]. response is just a wrapper around the array. All the types are stripped out when the typescript is converted to javascript, which is why it works fine at runtime.

Cant read React state data

I'm developing a react application and in my state I have the data saved that I try to read. When I JSON.stringify the device data "console.log"'it out, look like this:
{
"ActTime": 1509988664,
"ServerTime": "2017-11-06 18:17:44",
"Sunrise": "07:25",
"Sunset": "15:53",
"result": [
{
"AddjMulti": 1,
"AddjMulti2": 1,
"AddjValue": 0,
"AddjValue2": 0,
"BatteryLevel": 255,
"CustomImage": 0,
"Data": "On",
"Description": "",
"Favorite": 1,
"HardwareID": 2,
"HardwareName": "Controller",
"HardwareType": "OpenZWave USB",
"HardwareTypeVal": 21,
"HaveDimmer": true,
"HaveGroupCmd": true,
"HaveTimeout": false,
"ID": "00000501",
"Image": "Light",
"IsSubDevice": false,
"LastUpdate": "2017-11-06 15:42:00",
"Level": 0,
"LevelInt": 0,
"MaxDimLevel": 100,
"Name": "Vardagsrum",
"Notifications": "false",
"PlanID": "0",
"PlanIDs": [
0
],
"Protected": false,
"ShowNotifications": true,
"SignalLevel": "-",
"Status": "On",
"StrParam1": "",
"StrParam2": "",
"SubType": "Switch",
"SwitchType": "On/Off",
"SwitchTypeVal": 0,
"Timers": "false",
"Type": "Light/Switch",
"TypeImg": "lightbulb",
"Unit": 1,
"Used": 1,
"UsedByCamera": false,
"XOffset": "0",
"YOffset": "0",
"idx": "3"
}
],
"status": "OK",
"title": "Devices"
}
If I want to read the status data I just do: device['status'] I get "OK", but what if I want to access the result data in the device?
I thought that device['result'][0]['Status'] would give my 'Ok, but I just get Uncaught TypeError: Cannot read property '0' of undefined ???
How do I read the result data in the device??
To do this device['result'][0]['Status'] you want to ensure your device data is not a string but a proper JSON object. You could JSON.parse() to convert it if it's not already an object.
Also ensure the data is available before trying that.
Try to use map method over result array.
Something like this:
result.map((item,index)=>{
console.log(item[index].AddjMulti);
})

Trying to get a deeply embedded object from API object in JavaScript

I am trying to pull out the "quantity" value out of this API call with JavaScript however I cant seem to wrap my mind around it. Does any one feel up for the challenge?
{
"count": 5,
"results": [{
"listing_id": 216653218,
"state": "active",
"user_id": 57517426,
"category_id": 69150359,
"title": "Foodie Dice",
"description": "Some discription.",
"creation_tsz": 1419964059,
"ending_tsz": 1430414859,
"original_creation_tsz": 1419964059,
"last_modified_tsz": 1420033299,
"price": "25.00",
"currency_code": "USD",
"**quantity**": 1,
"tags": [],
"category_path": ["Geekery"],
"category_path_ids": [69150359],
"materials": [],
"shop_section_id": null,
"featured_rank": null,
"state_tsz": 1419964059,
"url": "https://www.etsy.com/listing/216653218/foodie-dice?utm_source=buddhabar&utm_medium=api&utm_campaign=api",
"views": 1,
"num_favorers": 0,
"shipping_template_id": null,
"processing_min": 1,
"processing_max": 1,
"who_made": "i_did",
"is_supply": "false",
"when_made": "2010_2015",
"is_private": false,
"recipient": null,
"occasion": null,
"style": null,
"non_taxable": false,
"is_customizable": false,
"is_digital": false,
"file_data": "",
"language": "en-US",
"has_variations": false,
"used_manufacturer": false,
"MainImage": {
"listing_image_id": 704444582,
"hex_code": null,
"red": null,
"green": null,
"blue": null,
"hue": null,
"saturation": null,
"brightness": null,
"is_black_and_white": null,
"creation_tsz": null,
"listing_id": 216653218,
"rank": null,
"url_75x75": "https://img0.etsystatic.com/048/0/10392050/il_75x75.704444582_poqv.jpg",
"url_170x135": "https://img0.etsystatic.com/048/0/10392050/il_170x135.704444582_poqv.jpg",
"url_570xN": "https://img0.etsystatic.com/048/0/10392050/il_570xN.704444582_poqv.jpg",
"url_fullxfull": "https://img0.etsystatic.com/048/0/10392050/il_fullxfull.704444582_poqv.jpg",
"full_height": null,
"full_width": null
}
},
Use a tool to beautify the output, it helps a lot.
One such tool here http://jsbeautifier.org/
As far as your question, you can access it here:
data.results[0].quantity

soundcloud api - how to check recorded track is active or not?

How can I check recorded track is uploaded and active for embed.
I want to show embed preview of track once it upload is done.
but I am getting 404 error from scPlayer api while resolving the url.
Is possible to track availability of track, based on that i can use sCplayer()
for resolving track.
Any help?
Thanks
Peter
I know in the /tracks resource there is a attribute called state which could be what you're looking for.
On their docs, the example value they give is finished, so maybe it would read uploading or processing before the track is ready. NB: I haven't tried this myself.
{
"id": 13158665,
"created_at": "2011/04/06 15:37:43 +0000",
"user_id": 3699101,
"duration": 18109,
"commentable": true,
"state": "finished",
"sharing": "public",
"tag_list": "soundcloud:source=iphone-record",
"permalink": "munching-at-tiannas-house",
"description": null,
"streamable": true,
"downloadable": true,
"genre": null,
"release": null,
"purchase_url": null,
"label_id": null,
"label_name": null,
"isrc": null,
"video_url": null,
"track_type": "recording",
"key_signature": null,
"bpm": null,
"title": "Munching at Tiannas house",
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "m4a",
"original_content_size": 10211857,
"license": "all-rights-reserved",
"uri": "http://api.soundcloud.com/tracks/13158665",
"permalink_url": "http://soundcloud.com/user2835985/munching-at-tiannas-house",
"artwork_url": null,
"waveform_url": "http://w1.sndcdn.com/fxguEjG4ax6B_m.png",
"user": {
"id": 3699101,
"permalink": "user2835985",
"username": "user2835985",
"uri": "http://api.soundcloud.com/users/3699101",
"permalink_url": "http://soundcloud.com/user2835985",
"avatar_url": "http://a1.sndcdn.com/images/default_avatar_large.png?142a848"
},
"stream_url": "http://api.soundcloud.com/tracks/13158665/stream",
"download_url": "http://api.soundcloud.com/tracks/13158665/download",
"playback_count": 0,
"download_count": 0,
"favoritings_count": 0,
"comment_count": 0,
"created_with": {
"id": 124,
"name": "SoundCloud iPhone",
"uri": "http://api.soundcloud.com/apps/124",
"permalink_url": "http://soundcloud.com/apps/iphone"
},
"attachments_uri": "http://api.soundcloud.com/tracks/13158665/attachments"
}
from: http://developers.soundcloud.com/docs/api/tracks
alternatively, there could be another value, like duration or stream_url that will read NULL until the track is ready.

Categories