Reverse an array of object? - javascript

How can i reverse this array using react native ? i tried myarray.reverse(); but I get below error message.
TypeError: undefined is not an object (evaluating 'myarray.reverse')
const myarray =
Array [
Object {
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": Object {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
Object {
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": Object {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]

try to remove Array and Object from the JSON. Works perfect for me.
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]
myarray.reverse()

Is the pasted code what you are actually getting back from the API?
The formatting/syntax is not correct. As others have stated you shouldn't have the 'Array' and 'Object' words inline like that. I think you're copying code from a terminal/console that added those words in.
If the response actually looks like this you won't have any problem using myaray.reverse()
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]

Related

Trouble handling nested JSON data

I have a JSON data and i'm having trouble with one nested object. You can see there is two metadata object, my aim is to get image link.
obj.metadata.url
is working, but this isn't work.
obj.metadata.metadata.image
what am i missing here?
{
"tokenId": "0",
"metadata": {
"url": "https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0",
"metadata": {
"name": "Illuminati #0",
"image": "https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png",
"attributes": [
{
"trait_type": "Background",
"value": "Stained Glass"
},
{
"trait_type": "Frames",
"value": "Stained Glass"
}
]
},
"tokenId": "0"
}
}
From your question it seems that you are dealing with JSON data instead of JavaScript objects. In order to get the attributes of JSON, you will first need to parse the JSON using JSON.parse(), then you can use . to get the properties you want.
data = {
"tokenId": "0",
"metadata": {
"url": "https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0",
"metadata": {
"name": "Illuminati #0",
"image": "https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png",
"attributes": [
{
"trait_type": "Background",
"value": "Stained Glass"
},
{
"trait_type": "Frames",
"value": "Stained Glass"
}
]
},
"tokenId": "0"
}
};
obj = JSON.parse(data);
console.log(obj.metadata.url)
// 'https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0'
console.log(obj.metadata.metadata.image);
// 'https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png'

Need to group data in Object based on value

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

React native json response

I am trying to print json responce in via console.log ,below is my json response but i want each element to print one by one like user.id or product.name
{
"user": [{
"id": "1",
"name": "User 1"
}, {
"id": "2",
"name": "User 2"
}],
"user_pictures": false,
"products": [{
"id": "1",
"name": "test abc"
}, {
"id": "2",
"name": "test abc 1"
}],
"purpose": ""
}
I am trying like this:
responseData.map((item)=>{
console.log(item.user.id)
})
but error is show in console
TypeError: responseData.map is not a function
responseData is the response in json when i call my fetch method
You can access id like this input.user[0].id.
Below is working code:
let input = {
"user": [{
"id": "1",
"name": "User 1"
}, {
"id": "2",
"name": "User 2"
}],
"user_pictures": false,
"products": [{
"id": "1",
"name": "test abc"
}, {
"id": "2",
"name": "test abc 1"
}],
"purpose": ""
};
console.log(input.user[0].id);
responseData is an object... you cant map over an object... responseData has 4 properties... users, user_pictures, products, purpose... of which, responseData.users and responseData.products are arrays that can be mapped over. user_pictures is a boolean and purpose is a string.
Its Works like this:
JSON.parse(responseData).user.map((item)=>{
console.log(item.id)
})
Thank guys

Javascript array value undefined?

I am currently working on a REST API / website project, where my REST API has to return an array of objects from the server, via a response and using GSON to make a Json array out of the data. However, when trying to get values from the javascript array for the website, I keep getting undefined. This is the array:
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [
{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}
],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [
{
"id": 1,
"number": "123124",
"info": "0x1"
}
]
}
];
When I try to call userArr[0].firstName, I get an error saying that it's undefined, even though the data is there. This is from a get call, which I am doing in my javascript from my REST API, which sends back this specific array. I have tried looping through the array, with multiple objects inside, however I am unable to retrieve any info at all.
Your userArr is an array of objects which do not have firstName property. They have only one property named 0x1 for some reason. And this 0x1 property has firstName property.
You can access firstName of 0x1 property using this notation:
userArr[0]["0x1"].firstName
Here is the working demo:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0]["0x1"].firstName);
By the way, there is a missing closing } bracket in the end of the array in your code.
I think if you write this code this way it is easy to understand and find the problem
var userArr =[
{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{"id": 1,"name": "Fodbold","people": ["0x1"]}],
"id": 1,
"address": {"id": 1,"street": "Street1","cityInfo": {"id": 1,"zipCode": "0555","city": "Scanning"},
"infoList": ["0x1","0x2"]},
"phones": [{"id": 1,"number": "123124","info": "0x1"}]
}
}
];
You also missing the last second bracket.
Then you could use this console.log(userArr[0]["0x1"].firstName);
try this one
userArr[0]["0x1"].firstName
Incase value "0x1" is dynamic, you can access it by using Object.keys(userArr[0])[0] to get the first key of the object.
Here is solution:
var userArr = [{
"0x1": {
"firstName": "Test1",
"lastName": "Test1",
"hobbies": [{
"id": 1,
"name": "Fodbold",
"people": [
"0x1"
]
}],
"id": 1,
"address": {
"id": 1,
"street": "Street1",
"cityInfo": {
"id": 1,
"zipCode": "0555",
"city": "Scanning"
},
"infoList": [
"0x1",
"0x2"
]
},
"phones": [{
"id": 1,
"number": "123124",
"info": "0x1"
}]
}
}];
console.log(userArr[0][Object.keys(userArr[0])[0]].firstName);

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 }

Categories