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!
4 Answers 4
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))
Comments
getData = function(data){
arr = data.data[0];
new_data = []
for(var item in arr){
new_data.push(arr[item])
}
}
Hope this will help you.
Comments
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))
Comments
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));
2 Comments
responseData is undefined or null or your trying to handle the responseData outside of the async all. I've added default values to prevent errors, but you should why the responseData is undefined, or the data inside it is.
obj.data[0]will give you your array