I have a response from the server that looks like this
[
{
"metric":{
"id":"b66178b8-dc18-11e8-9f8b-f2801f1b9fd1",
"name":"Detector de fum bucatarie",
"metricValueType":"DOUBLE",
"metricType":"DEVICE_VALUE",
"groupUUID":null,
"projectUUID":null,
"companyUUID":"ccab28ed-3dcf-411f-8748-ec7740ae559c",
"unit":null,
"formula":null
},
"data":{
"1550150771819":"10.310835857351371"
}
}
]
Data property contains a hashMap with Timestamp and a Value.
When I try to get any value I recive this error:
myErrorTypeError: undefined is not an object (evaluating 'metricValues.metric.id')
How can I access a property ? I tried both methods :
metricValues.metric.id
and
metricValues["metric"]["id"]
How can I get the hashMap values?
I already tried this :
const timestamp = Object.keys(metricValues.data)[0];
const values = Object.values(metricValues.data)[0];
Your data is an array of objects. So even though your data has only one object, still it is an array of objects.
your object is at index 0 of the array.
You can access the metric Id as follows,
metricValues[0].metric.id
Try This (put that [0])
metricValues[0].metric.id
Your response from the server is an array. And the metric object is in the first element of that array.
To access the id inside the metric object you need to pass the index at which that object is present in the array which is 0 here.
That's why use :
metricValues[0].metric.id
Related
I have the following JSON format
{
"name":"xyz",
"age-group":"bb"
}
How to get sort out this JSON
I use the following code
const array = [{ "name":"xyz", "age-group":"bb"} ]
array.map((element) => {
Console.log(element.age-group)
});
I got an error:
Can't find variable: group
1st thing is you can't map object.
and in your case you set json object in array and then you are maping it.
so it must be like:
array[0].name;
but in second property, it has hyphen which looks like "age-group" to access object property containing hyphen is:
array[0].obj["age-group"] //this is return `bb`
so in your code it will be:
array.map((element) => {
console.log(element.obj["age-group"])
});
to access object property with hyphen(-) you need to use notation with square brackets.
I don't understand something and need explanations please !
I have a datatable and selection of lines generate in my .ts an array of Operation object. here is my object class :
export class Operation {
id: number;
name: string;
}
this is the declaration of array :
selectedOperations: Operation[];
when I log in console before extraction of ids, I have this :
this.selectedOperations = {"selected":[{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}]}
and when I want to extract ids with this :
let ids = this.selectedOperations.map(o => o.id);
I have an exception =>
this.selectedOperations.map is not a function
It's not the first time I have this problem and I'd like to understand why. I search some reasons and found differences between Array and object[] ? I think it's not really an array because there is the {"selected": before the array...
Can someone tell me the thing and help me for extract ids ?
thanks a lot !
{"selected":[{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}]} => this is of type object, whereas your array declaration looks like this selectedOperations: Operation[];
You either directly assign the array to your variable:
this.selectedOperations = [{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}];
Or you can change your variable type to any or object:
selectedOperations: any;
this.selectedOperations = {"selected":[{"id":1,"name":"My name 1"},{"id":3,"name":"My name 3"}]}
const ids = this.selectedOperations.selected.map(o => o.id);
this.selectedOperations.map is not a function error is caused by the initialization, map function is reserved for arrays, therefore it throws an error when you try to use it on an object type variable.
I would recommend the first approach by the way, declaring a variable as any or object is contradicting with the purpose of Typescript.
You need to make some improvements to the code. In order to get the ids, you need to add selected to this.selectedOperations. See below.
let ids = this.selectedOperations.selected.map(o => o.id);
I'm reading back record sets in an express server using the node mssql package. Reading back the values outputs an array of Json objects as expected.
Now I need to modify the Email propoerty value of each Json object. So I tried looping through the recordset and changing the value at each index:
var request = new sql.Request(sql.globalConnection);
request.input('p_email', sql.VarChar(50), userEmail);
request.execute('GetDDMUserProfile', function(err, recordsets, returnValue) {
for (var i = 0; i < recordsets.length; i++){
recordsets[i].Email = "joe#gmail.com";
}
console.log(recordsets);
});
But instead of modifying the Emailvalue of each Json object, this code just appends a new email property to the last Json object.
How can you map new property values to an array of JSON objects?
Example output:
An example of the output is shown below, where a new Email property has been added to the end of the array instead of changing each existing property value:
[
[
{
ID:[
4
],
UserName:"Brian",
Email:"joe#gmail.com"
},
{
ID:[
5
],
UserName:"Brian",
Email:"joe#gmail.com"
}
Email:'joe#gmail.com' ]
]
The issue here is that your dataset appears to not be an array of JSON objects but, rather, an array of arrays of JSON objects. If you know for certain that you'll always have only one array in the top-most array, then you can solve the problem like this:
recordsets[0][i].Email = "joe#gmail.com";
to always target the first array in the top-most array. However, if the top-most array could potentially have more than one array, that'll be a different kind of issue to solve.
The below is my data, its type is object, I am not able to get my data after stringifying and parsing too...how can I get message alone using nodejs.
[ { ID: '361',Message: 'customg' } ]
I guess what you want to say is this. You got an array of object(s) like this:
var myarray =[ { ID: '361',Message: 'customg' } ] ;
stringifying the json object using JSON.stringify(myarray), gives :
"[{\"ID\":\"361\",\"Message\":\"customg\"}]"
parsing back using JSON.parse ("[{\"ID\":\"361\",\"Message\":\"customg\"}]"), returns your original object.
Now to access the 'Message' member, you need to access the first item in the array, then the Message property of the object, like this:
var msg =myarray [0].Message ;
This code assumes, you got an object with a property Message as the first element of the array.
Your data is,
data = [ { ID: '361',Message: 'customg' } ]
data variable contains list of Objects(Here there is only one object in list).
var msg = data[0].Message // You will get message property
In your case you already have list of objects, so no need to stringify/parse the list.
JSON.stringify() : used when you want to convert your JSON object to string.
JSON.parse() : used when you want JSON object from string.(given that string contains proper JSON object)
I have a object which is retrieved from the local storage.Now i want to iterate that object and retrieve each key and set that key to another object as an array.
I mean
var a=localStorageService.get("formStructure");
for(var obj in a)
{
if(a.hasOwnProperty(obj){
//need to retrieve key value
form['key']=[];
}
}
Now i need to iterate 'a' and assign to a another object. Output must be
var form={
Test:[],
form:[]
}
You need to Stringify before need to store data on localStorage and after retrieval you need to parse it.
Look the following example.
Setting object to localStorage in normal way
var form={
Test:[],
form:[]
};
localStorage.setItem('formStructure', form);
Getting value from LocalStorage after normal way.
localStorage.getItem('formStructure');
//Output is as "[object Object]"
But if we Stringfy the object as JSON the then save it as follows
localStorage.setItem('formStructure', JSON.stringify(form));
Then at the time of if we parse it again we will get the proper object
JSON.parse(localStorage.getItem('formStructure'));
Output as Object {Test: Array[0], form: Array[0]}. Proper object structure.
EDIT: For iteration of you object iterate as
for(var obj in a) {
if(a.hasOwnProperty(obj)){
form[obj]=[];
}
}