2

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

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

The above code given by Cristian Traina worked fine. I will use that
Thank you so much, brother! Your answer work for me. I am getting response like "[{"id":1,"title":"\u30aa\u30b9"},{"id":2,"title":"\u30e1\u30b9"},{"id":3,"title":"\u30aa\u30b9\/\u53bb\u52e2\u6e08"},{"id":4,"title":"\u30e1\u30b9\/\u907f\u598a\u6e08"},{"id":5,"title":"\u4ed6"}]" And your answer gave me perfect solution.
5

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);

2 Comments

I am new to Javacript, just trying to learn through React Native.
Let me give you an advice, just don't start with React Native. That's an advanced topic, it solves some problems that you aren't aware of
2

Using Object.entries, you can avoid the extra hash lookup on every item.

const x = { foo: 11, bar: 42 };
const result = Object.entries(x).map(([key, val]) => ({
  [key]: val
}));
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.