Retrieving JSON response data with dynamic key [duplicate] - javascript

This question already has answers here:
Accessing a JavaScript's object property without knowing that property name
(3 answers)
How to access the first property of a Javascript object?
(23 answers)
Getting the first index of an object
(14 answers)
Closed 3 years ago.
I'm calling an API in my application and need to drill down the JSON response. Within it there is a random string that changes so I can't hardcode the value. Is there a way I can access dataset1 no matter what the random string is?
{
"data": {
"Random String that Changes": {
"dataset1": {
"date": {...}
},
"dataset2":{
"date": {...}
}
}
},
"something else": {
...
},
"something else": {
...
}
}
Previously I was hard coding the drill down like such:
this.props.data.randomData['Random String that Changes'].dataset1.date
Also tried:
this.props.data.randomData[0].dataset1.date

You can get all the keys of the object using
const keys = Object.keys(this.props.data);
Now keys is an array of all keys , but if you json always only has 1 key, you can get your data using
this.props.data.randomData[keys[0]].dataset1.date

You can get dataset1
const values = Object.values(this.props.data)
console.log(values[0]['dataset1'])
Make sure that your json includes the "Random String that changes" at first place as shown in your above format.
Reference: Object.values

Try accessing the object like this :
const obj = this.props.data;
obj[Object.keys(obj)[0]].dataset1.date
Reference: How to access the first property of an object in Javascript?

Consider sample data in myObj.
var myObj = {
"data" : {
"Random String that Changes": {
"dataset1": {
"date": "123"
},
"dataset2":{
"date": "123"
}
}
}
}
var randomString =myObj[Object.keys(myObj)[0]];
var dataset1Date =randomString[Object.keys(randomString)[0]].dataset1.date;
console.log(dataset1Date);
So in this way you can access the date which you are trying with
this.props.data.randomData['Random String that Changes'].dataset1.date

Please check the below code for the solution.
var response = {
"data": {
"Random String that Changes": {
"dataset1": {
"date": {...}
},
"dataset2":{
"date": {...}
}
}
},
"something else": {
...
},
"something else": {
...
}
};
var dataInRandomKey = response.data[Object.keys(response.data)[0]];
Now, you have the whole JSON object (in current example, response['data']['Random String that Changes']) in dataInRandomKey variable.

You can try for in loop
var a = {
"data": {
"Random String that Changes": {
"dataset1": {
"date": {...}
},
"dataset2":{
"date": {...}
}
}
},
"something else": {
...
},
"something else": {
...
}
}
var response = a.data;
for(var key in response) {
console.log(response[key].dataset1);
}

Related

Javascript eval alternative for reading object [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 6 months ago.
I am trying to read values from JSON Object using a function that is dynamic.
Sample JSON Object -
var test =
{
"test1": {
"test2": "value2"
},
"test3": {
"test4": {
"test5": "value5"
}
}
}
Now I need to read the test5 value and test2 value so I created the below method and called it twice by passing the argument.
readValue('test1.test2');
readValue('test3.test4.test5');
function readValue(val){
console.log(eval(`test.${val}`));
}
This code is working fine, I am able to get the output.
But is there any alternative to use eval here ??
Better than eval, split your compound key by a dot and iterate it:
let val = (obj, keys) => keys.split('.').reduce(Reflect.get, obj)
var test =
{
"test1": {
"test2": "value2"
},
"test3": {
"test4": {
"test5": "value5"
}
}
}
console.log(val(test, 'test1.test2'))
console.log(val(test, 'test3.test4.test5'))

How do I dynamically get the values from Objects in Javascript? [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 3 years ago.
So say that I have an array of objects with objects within the objects. This data is dynamic, i.e the keys wont be the same , it may differ.
For example:
[
{
"uuid": "53e7202c-28c8-4083-b910-a92c946a7626",
"extraIdentifiers": {
"National ID": "NAT2804"
},
"givenName": "Krishnan",
"customAttribute": null,
"age": "32"
},
{
"uuid": "9717ec58-8f87-4305-a57b-bed54301def7",
"extraIdentifiers": {
"National ID": "NAT2805"
},
"givenName": "Dale",
"customAttribute": null,
"age": "32"
},
{
"uuid": "d3563522-927d-4ff0-b697-eb164289a77d",
"extraIdentifiers": {
"National ID": "NAT2806"
},
"givenName": "David",
"age": "32"
}
]
Now I have a function which will get the value from one of the keys. For eg , I want to get the givenName so it will return David for example.
This is the code for it:
$scope.sortPatient = function (param) {
$scope.results.map(function (currentObj) {
console.log(currentObj[param]);
})
};
The $scope.results will hold the above JSON Obj. When calling sortPatient I would call it by passing the key whose value I want. For eg: sortPatient('givenName') or sortPatient('age').
This would log Dale or 32 in the console. But if I call sortPatient('extraIdentifiers.National ID') it does not log NAT2804 in the console, but logs undefined. I also tried calling it like sortPatient('extraIdentifiers[National ID]') but it still shows undefined.
How would I be able to get the values of keys inside keys? I also cannot change the way the function is being called. I can only change its definition., but I'm not able to get the values of keys inside complex objects.
I would pass an array with keys to your method instead, and then check if the object contains the given key path.
$scope.sortPatient = function (params) {
$scope.results.map(function (currentObj) {
var res = currentObj;
params.forEach(function(param){
if(res[param]) res = res[param];
})
console.log("res",res);
})
};
$scope.sortPatient(['extraIdentifiers','National ID']);

How do I find a JSON value with a specific ID?

I have an object and I’m trying to find a specific value using an ID in ECMAScript6.
I’ve tried something like this: myvalue = this.json.find(x => x == '1234');
The JSON looks something like this:
{
"results": [
{
"abcde1234": {
"value": 4
}
},
{
"zxcv4567": {
"value": 2
}
}
]
}
All the examples I’ve found can only find off named key-value pairs.
Try
json.results.find(x => /1234/.test(Object.keys(x)[0]));
json = {
"results": [
{
"abcde1234": {
"value": 4
}
},
{
"zxcv4567": {
"value": 2
}
}
]
}
let r = json.results.find(x => /1234/.test(Object.keys(x)[0]));
console.log(r);
const json = {
'1234': { 'value' : 4},
'5678': { 'value' : 10}
};
const value = json['1234'];
console.log(value);
The JSON data doesn't seem proper.
But in case you are finding by key, you can directly access this, something like:
Parsed JSON maps directly to JavaScript types: Object, Array, boolean, string, number, null. Your example used find() which is (normally) a method used with arrays. If your JSON was structured like this, you could expect to use find:
const jsonString = '["a", "b", "c"]';
const jsonData = JSON.parse(jsonString);
jsonData.find(x => x === "a"); // "a"
But it seems like your data is structured as an object, so you can use normal property access:
const jsonString = '{"1234": {"value": 4}, "5678": {"value": 10}}';
const jsonData = JSON.parse(jsonString);
jsonData["1234"] // {value: 4}
jsonData["1234"].value // 4
EDIT
OP changed the data example, so the above code is less directly applicable, but the general point is: once you parse it, it's just javascript.

How to parse all JSON strings in a JavaScript object

I have 1 JavaScript object like this:
result = {
"status": "success",
"message": "Get successful!",
"data": {
"name":"Hello world",
"school": {
"name":"LHP",
"address":"HCM"
},
"class": "[{\"text\":\"Math\",\"code\":\"math124\"},{\"text\":\"Libra\",\"code\":\"libra124\"}]",
"student": "{\"time_range\":{\"type\":\"select\",\"text\":\"Today\",\"value\":[{\"code\":\"in_today\",\"text\":\"In Today\"}]}}"
}
}
So I have to parse class and student separately:
result.data.class = JSON.parse(result.data.class);
result.data.student = JSON.parse(result.data.student);
Is there other way to parse the whole result variable or make this step shorter/better?
Thanks
You could loop through the data property's children and parse them.
for (var i = 0; i < Object.keys(result.data).length; i++) {
try {
result.data[Object.keys(result.data)[i]] = JSON.parse(result.data[Object.keys(result.data)[i]]);
} catch (error) {} // it's already JSON
}
But I'd only do that if you're sure you'll only ever have to deal with stringified JSON in the data property of your object.

Create String From JSON object KEYS - Vanilla JavaScript or lodash [duplicate]

This question already has an answer here:
Recursively list all object property paths from JSON [duplicate]
(1 answer)
Closed 6 years ago.
need some help.
I have a json object and I want to create an string array with keys of the object.
json Object
{
"FEATURES": {
"APP_DASHBOARD": {
"MENU_TITLE": "Dashboard",
"HEAD_TITLE": "Dashboard",
"HEAD_DESC": "Welcome to briteplan"
},
"APP_TEAM": {
"MENU_TITLE": "Teams",
"HEAD_TITLE": "Teams",
"HEAD_DESC": "",
"TOOL_TIPS": {
"TEAM_REFRESH": "Refresh teams",
"TEAM_ADD": "Add new team",
"TEAM_EDIT": "Edit team",
"TEAM_REMOVE": "Remove team",
"MEMBER_REMOVE" : "Remove team member",
"MEMBER_LEAD" : "Team lead",
"AVL_MEMBERS_REFRESH" : "Refresh available members"
},
"CONTENT": {
"TEAMS_TITLE": "Teams",
"MEMBERS_TITLE": "Members",
"AVL_MEMBERS_TITLE": "Available team members"
}
}
},
"GENERAL": {
"SEARCH_PLACEHOLDER": "Search ..."
}
}
I would like to generate a array that looks like this:
var myArray = [
'FEATURES.APP_TEAM.MENU_TITLE',
'FEATURES.APP_TEAM.HEAD_TITLE',
'FEATURES.APP_TEAM.HEAD_DESC',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REFRESH',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_ADD',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_EDIT',
'FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REMOVE',
];
Not all values is included, but I think you get the Idea. The main thing is I Will know the I have "FEATURES" in the object and I will know the feature name "APP_TEAM", but I don't know the nesting level within that feature.
Hope anyone can help me.
recursion:
function getKeys (o) {
var keys = [];
for (var prop in o) {
if(o.hasOwnProperty(prop)) {
if(typeof o[prop] === 'object') {
getKeys(o[prop]).forEach(function (nestedProp) {
keys.push(prop + '.' + nestedProp);
});
}
else {
keys.push(prop);
}
}
}
return keys;
}
on the above object, returns:
[
"FEATURES.APP_DASHBOARD.MENU_TITLE",
"FEATURES.APP_DASHBOARD.HEAD_TITLE",
"FEATURES.APP_DASHBOARD.HEAD_DESC",
"FEATURES.APP_TEAM.MENU_TITLE",
"FEATURES.APP_TEAM.HEAD_TITLE",
"FEATURES.APP_TEAM.HEAD_DESC",
"FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REFRESH",
"FEATURES.APP_TEAM.TOOL_TIPS.TEAM_ADD",
"FEATURES.APP_TEAM.TOOL_TIPS.TEAM_EDIT",
"FEATURES.APP_TEAM.TOOL_TIPS.TEAM_REMOVE",
"FEATURES.APP_TEAM.TOOL_TIPS.MEMBER_REMOVE",
"FEATURES.APP_TEAM.TOOL_TIPS.MEMBER_LEAD",
"FEATURES.APP_TEAM.TOOL_TIPS.AVL_MEMBERS_REFRESH",
"FEATURES.APP_TEAM.CONTENT.TEAMS_TITLE",
"FEATURES.APP_TEAM.CONTENT.MEMBERS_TITLE",
"FEATURES.APP_TEAM.CONTENT.AVL_MEMBERS_TITLE",
"GENERAL.SEARCH_PLACEHOLDER"
]

Categories