Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON object into an array in React Native

I am getting a JSON object from Firebase. I am trying to convert it into an array of objects.

I can solve this by getting childs from Firebase one-by-one and add them into array however, that is not a good practice for my case.

The format of JSON object is as following:

key: {
      id1: {some stuff here},
      id2: {some other stuff},
    ...
}

Now what I want to get from this JSON object is :

arrayName: [
         {id1:{some stuff here},
         id2:{some other stuff}
]

Hope my description if fully understandable. Any help would be appreciated

like image 693
Javid Haji-zada Avatar asked Mar 20 '26 14:03

Javid Haji-zada


2 Answers

This code worked for me.

const JSONString = res.data;
      object = JSON.parse(JSONString);
      array = Object.keys(object).map(function(k) {
        return object[k];
      });

Where res.data is the response I am getting from an api

like image 139
Nick.K Avatar answered Mar 22 '26 05:03

Nick.K


This is just plain javascript, it has nothing to do with react native. By the way, you can use Object.keys to get an array with all the keys, then map the strings as objects:

const x = {foo: 11, bar: 42};
const result = Object.keys(x).map(key => ({[key]: x[key]}));
console.log(result);
like image 25
Cristian Traìna Avatar answered Mar 22 '26 05:03

Cristian Traìna