'accessing nested array key,value from json in javascript
I am new in javascript. It may be a basic thing but I am stuck with it. here is my json:
{
"statusCode": 200,
"status": "success",
"data": [
[
{
"city": "Alexandria",
"country": "Egypt",
},
{
"city": "Alexandria",
"country": "Egypt",
},]]
I want to access this:
0: {city: "Alexandria", country: "Egypt"}
1: {city: "Antalya", country: "Turkey"}
I tried this code :
getData = function (data) {
keys = Object.keys(data[0]);
data = [];
keys.forEach(function (key) {
data.push(key);
});
return data;
}
which returns this:
0: "0"
1: "1"
2: "2"
3: "3"
4: "4"
5: "5"
6: "6
please help me!
Solution 1:[1]
You can use Destructuring assignment to get first element of response's data
array as result
:
const response = {
"statusCode": 200,
"status": "success",
"data": [
[{
"city": "Alexandria",
"country": "Egypt",
},
{
"city": "Alexandria",
"country": "Egypt",
},
]
]
}
const getData = ({ data: [result] = [[]] }) => result
console.log(getData(response))
Solution 2:[2]
getData = function(data){
arr = data.data[0];
new_data = []
for(var item in arr){
new_data.push(arr[item])
}
}
Hope this will help you.
Solution 3:[3]
First, your data[0]
is an array, then Object.keys(array)
will return an array of index
of that array
. Ex:
array= [{x: 1}, {x: 2}, {x: 3}]
Object.keys(array) // ['0', '1', '2']
So what you pushed to the return array are just the index like what you showed.
Second, you should use the different variable name to avoid misunderstanding. In this case, is data
variable.
I updated the function
const object = {"statusCode": 200,"status": "success","data": [[{"city": "Alexandria","country": "Egypt",},{"city": "Alexandria","country": "Egypt",},]]}
getData = function (arr) {
data = []
arr[0].forEach(function (key) {
data.push(key);
});
return data
}
console.log(getData(object.data))
Solution 4:[4]
You can use destructuring to extract the data
from the object and the array:
const getData = ({ data: [data] = [] } = {}) => data;
const response = {"statusCode":200,"status":"success","data":[[{"city":"Alexandria","country":"Egypt"},{"city":"Alexandria","country":"Egypt"}]]};
console.log(getData(response));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Nikhil Unni |
Solution 3 | |
Solution 4 |