React Native Converting JSON objects to array [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I fetch some data from the server and the data response comes in this form
[
{
"_id": "5dcb1495daa062304c60c7b0",
"weightTracking": 97,
"weightTrackingDate": "Nov 12"
},
{
"_id": "5dcb14eadaa062304c60c7b1",
"weightTracking": 96,
"weightTrackingDate": "Nov 13"
},
{
"_id": "5dcb161ddaa062304c60c7b2",
"weightTracking": 95,
"weightTrackingDate": "Nov 14"
},
{
"_id": "5dcb1c6cdaa062304c60c7b3",
"weightTracking": 94,
"weightTrackingDate": "Nov 15"
},
]
I want to be able to use this data in my app like that
data={{
labels: ['Nov 12', 'Nov 13', 'Nov 14', 'Nov 15'],
datasets: [
{
data: [
97,
96,
95,
94,
],
},
],
}}
Like [weightTracking] , [weightTrackingDate] in Javascript or react-native
how can I do that? is it possible to do that?

// assuming that data fetched from the server is inside the variable called 'response'
const response = [
{
"_id": "5dcb1495daa062304c60c7b0",
"weightTracking": 97,
"weightTrackingDate": "Nov 12"
},
{
"_id": "5dcb14eadaa062304c60c7b1",
"weightTracking": 96,
"weightTrackingDate": "Nov 13"
},
{
"_id": "5dcb161ddaa062304c60c7b2",
"weightTracking": 95,
"weightTrackingDate": "Nov 14"
},
{
"_id": "5dcb1c6cdaa062304c60c7b3",
"weightTracking": 94,
"weightTrackingDate": "Nov 15"
},
]
const labels = [];
const datasets = [];
response.forEach(item => {
labels.push(item.weightTrackingDate)
datasets.push(item.weightTracking)
})
const data = {
labels: labels,
datasets: [{
data: datasets,
}]
}
Edit: instead of a straightforward answer, I'll add some comments too:
As #byxor stated, it's not at all related to React Native. It's a simple JavaScript task. React Native uses JavaScript but don't get those two confused. Arrays, objects, loops, etc are a feature of the language, not the framework.
You could also use a for() loop for this, instead of using forEach, but it's totally up to you. It mostly comes down to code readability.

This should get you the data in the format you specified
let originalArray = <Your array>;
let data = originalArray.reduce((newObj, currentElement) => {
newObj.labels.push(currentElement.weightTrackingDate);
newObj.datasets[0].data.push(currenElement.weightTracking);
return newObj;
}, { labels: [], datasets: [{data: []}] });

You can use the below code to achieve this:
let arr = [
{
"_id": "5dcb1495daa062304c60c7b0",
"weightTracking": 97,
"weightTrackingDate": "Nov 12"
},
{
"_id": "5dcb14eadaa062304c60c7b1",
"weightTracking": 96,
"weightTrackingDate": "Nov 13"
},
{
"_id": "5dcb161ddaa062304c60c7b2",
"weightTracking": 95,
"weightTrackingDate": "Nov 14"
},
{
"_id": "5dcb1c6cdaa062304c60c7b3",
"weightTracking": 94,
"weightTrackingDate": "Nov 15"
},
];
console.log(arr);
let outarr = [];
let labeles = [];
let dataset = [];
arr.forEach( e => {
labeles.push(e.weightTracking);
dataset.push(e.weightTrackingDate);
})
console.log("----------------------");
console.log(labeles);
console.log(dataset);
let data={};
data.labels = labeles;
data.datasets = {}
data.datasets.data = dataset;
console.log(data);

Related

fetch request shows undefined when trying to access an array within an array (svelte)

I'm having trouble understanding what I'm missing when trying to access this data from an API the data I'm trying to access is an array within an array but when I try to access it, it will either show me [object, object] or undefined.
the svelte store
import { writable } from "svelte/store";
export const leagueStandings = writable([]);
const fetchStandings= async () => {
const url = 'https://soccer.sportmonks.com/api/v2.0/standings/season/17420?api_token=API_KEY';
const res = await fetch(url);
const data = await res.json();
leagueStandings.set(data.data);
}
fetchStandings();
the svelte component
<script>
import {leagueStandings} from "../../stores/league-standings-stores"
console.log(leagueStandings)
let tablePositions = leagueStandings.map($leagueStandings => $leagueStandings.standings)
console.log(tablePositions)
</script>
{#each tablePositions as tablePosition}
<h2>{tablePosition.position}</h2>
{/each}
The API with, im trying to get my data from "standings". i can the content to show in a console.log() but cant actually access the values :(
{
"data": [
{
"id": 77448322,
"name": "Regular Season",
"league_id": 8,
"season_id": 17420,
"round_id": 202038,
"round_name": 38,
"type": "Group Stage",
"stage_id": 77448322,
"stage_name": "Regular Season",
"resource": "stage",
"standings": {
"data": [
{
"position": 1,
"team_id": 9,
"team_name": "Manchester City",
"round_id": 202038,
"round_name": 38,
"group_id": null,
"group_name": null,
"overall": {
"games_played": 38,
"won": 27,
"draw": 5,
"lost": 6,
"goals_scored": 83,
"goals_against": 32,
"points": 86
},
"home": {
"games_played": 19,
"won": 13,
"draw": 2,
"lost": 4,
"goals_scored": 43,
"goals_against": 17,
"points": 41
},
"away": {
"games_played": 19,
"won": 14,
"draw": 3,
"lost": 2,
"goals_scored": 40,
"goals_against": 15,
"points": 45
},
"total": {
"goal_difference": "51",
"points": 86
},
"result": "UEFA Champions League",
"points": 86,
"recent_form": "WLWLW",
"status": null
},
The standings property is an object with property data that is an array but you don't seem to be accounting for such a structure.
If you want to flatten all the standings.data arrays into a single list, try this...
const tablePositions = leagueStandings.flatMap(
({ standings: { data } }) => data
);

Get specific value from an object and push it into an array

Hello I have an obj(came from JSON parsed) and I'm trying to get only one value from it the "VALUE"(default.timelineData)
for example from this obj I want an array [38,35,87,63,34].
I tried with Object.values and also to pass it to an array and then work with it but it's very complicated and I believe there is a shortcut to it. function without success hopes for help thanks...
{
"default":{
"timelineData":[
{
"time":"1610323200",
"formattedTime":"Jan 11, 2021",
"formattedAxisTime":"Jan 11",
"value":[
38
],
"hasData":[
true
],
"formattedValue":[
"38"
]
},
{
"time":"1610409600",
"formattedTime":"Jan 12, 2021",
"formattedAxisTime":"Jan 12",
"value":[
35
],
"hasData":[
true
],
"formattedValue":[
"35"
]
},
{
"time":"1610496000",
"formattedTime":"Jan 13, 2021",
"formattedAxisTime":"Jan 13",
"value":[
87
],
"hasData":[
true
],
"formattedValue":[
"87"
]
},
{
"time":"1610582400",
"formattedTime":"Jan 14, 2021",
"formattedAxisTime":"Jan 14",
"value":[
63
],
"hasData":[
true
],
"formattedValue":[
"63"
]
},
{
"time":"1610668800",
"formattedTime":"Jan 15, 2021",
"formattedAxisTime":"Jan 15",
"value":[
34
],
"hasData":[
true
],
"formattedValue":[
"34"
]
}
],
"averages":[
]
}
}
The property you are trying to access is an Array. You can use Array.map to iterate through the elements and push the returned values into a new array at the same time. Like this:
const values = obj.default.timelineData.map(item => item.value[0])
console.log(values); // [38, 35, 87, 63, 34]

How to extract all first objects for an object of array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I make an axios request like that :
async get() {
await this.$axios.get(`my_api_url`)
.then(response => {
this.data = response.data;
}).catch(() => { console.log('error') })
},
It returns a response with these data:
{
"Apple": [
{
"id": 26,
"name": "Apple",
"date_in": "2020-07-01"
},
{
"id": 23,
"name": "Apple",
"date_in": "2020-06-01"
}
],
"Cherry": [
{
"id": 24,
"name": "Cherry",
"date_in": "2020-06-01"
}
],
"Banana": [
{
"id": 25,
"name": "Banana",
"date_in": "2020-06-01"
}
]
}
I would like to be able to browse this object and keep only the first object in each table. Then put the selected objects in a new table.
Is it possible to do this?
function GetObjects(input){
var output = [];
for(let key in input){
output.push(input[key][0]);
}
return output;
}
If I understand your question correctly
Like that?
const src = {"Apple":[{"id":26,"name":"Apple","date_in":"2020-07-01"},{"id":23,"name":"Apple","date_in":"2020-06-01"}],"Cherry":[{"id":24,"name":"Cherry","date_in":"2020-06-01"}],"Banana":[{"id":25,"name":"Banana","date_in":"2020-06-01"}]},
resultArr = Object.values(src).map(([o]) => o)
console.log(resultArr)
.as-console-wrapper{min-height:100%;}
Or, like that?
const src = {"Apple":[{"id":26,"name":"Apple","date_in":"2020-07-01"},{"id":23,"name":"Apple","date_in":"2020-06-01"}],"Cherry":[{"id":24,"name":"Cherry","date_in":"2020-06-01"}],"Banana":[{"id":25,"name":"Banana","date_in":"2020-06-01"}]},
resultObj = Object.entries(src).reduce((r,[key,[o]]) =>
(r[key] = o,r),{})
console.log(resultObj)
.as-console-wrapper{min-height:100%;}
You can get the results like:
const data = {
"Apple": [
{
"id": 26,
"name": "Apple",
"date_in": "2020-07-01"
},
{
"id": 23,
"name": "Apple",
"date_in": "2020-06-01"
}
],
"Cherry": [
{
"id": 24,
"name": "Cherry",
"date_in": "2020-06-01"
}
],
"Banana": [
{
"id": 25,
"name": "Banana",
"date_in": "2020-06-01"
}
]
}
const results = Object.keys(data).filter(item => data[item][0]).map(item => data[item][0]);
console.log(results);

Getting PHP multidimensional array in to Javascript using JSON?

I need to get an array to display the following way:
var categories = data.categories;
for(a = 0; a < data.count; a++){
var names[a] = data.name[a];
var values[a] = data.value[a];
}
There will be one "Categories" array, for example "May 2017","June 2017","July 2017","August 2017","September 2017". Then there may be 3/4 arrays containing "Name" and "Values" and I want these to loop through a loop to loop and assign these to variables.
At the moment I'm getting 'Undefined" in all variables.
My output in php is currently:
[
[{
"name": "Leads",
"data": [524, 419, 502, 598, 873],
"color": "#00afef"
}, {
"name": "Purchases",
"data": [37, 18, 32, 36, 44],
"color": "#f00"
}], {
"categories": ["May 2017", "June 2017", "July 2017", "August 2017", "September 2017"]
}
]
The JSON you're getting back has horrible schema and you're doing weird things in JS. Hopefully the following will get you back on track:
var data = [
[{
"name": "Leads",
"data": [524, 419, 502, 598, 873],
"color": "#00afef"
}, {
"name": "Purchases",
"data": [37, 18, 32, 36, 44],
"color": "#f00"
}], {
"categories": ["May 2017", "June 2017", "July 2017", "August 2017", "September 2017"]
}
];
var categories = data[1].categories;
var names = [];
var values = [];
for (var a = 0; a < data[0].length; a++) {
names.push(data[0][a].name);
values.push(data[0][a]);
}
console.log(categories);
console.log(names);
console.log(values);

Json structure with Javascript Mapping

Is any tool or online editor available so that it specify how to access a json element.For example if i provide json as input ,then we should get an output which will specify each item how can we access through javascript
Example
Assume Input is
var myList={ "vehicleList": { "Vehicle": [ { "vehicleId": 88, "vehicleName": "veh1", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1001, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1002, "AlertName": "Sudden acceleration", "Alertcount": 40 } ] }, { "vehicleId": 87, "vehicleName": "veh2", "totalEvents": 11, "medium": 4, "Severe": 7, "Category": [ { "AlertId": 1003, "AlertName": "Overspeed", "Alertcount": 30}, { "AlertId": 1004, "AlertName": "Drunk", "Alertcount": 10 } ] }, { "vehicleId": 87, "vehicleName": "veh3", "totalEvents": 10, "medium": 2, "Severe": 2, "Category": [ { "AlertId": 1007, "AlertName": "Overspeed", "Alertcount": 10 }, { "AlertId": 1008, "AlertName": "Overspeed", "Alertcount": 77 } ] }, { "vehicleId": 86, "vehicleName": "veh4", "totalEvents": 11, "medium": 4, "Severe": 5, "Category": [ { "AlertId": 1009, "AlertName": "Overspeed", "Alertcount": 17 }, { "AlertId": 1010, "AlertName": "HighSpeed", "Alertcount": 10 } ] } ] } };
Output should be a structure,which will specify like
myList.vehicleList.Vehicle[3].Severe;
It seems like you looking backward means providing the value you need what will be the expression to get the value. I don't have a solution for that.
But I would like to suggest json is very easy to read, may be you are having trouble due to long chunk of string. Try this website(editor) http://jsonlint.com/ this will validate your json and give you in more readable form. Hope this will help you in one or other way.

Categories

Resources