skip to Main Content

I want to transform a firebase object to an array like this :

here is a link to the fiddle with an example https://jsfiddle.net/vfra1yp5/

0: Object { first: "https://google.com", last: "google" }
to 
[
      {
        first: "https://google.com",
        last: "google",
      },

    ]

I have tried

var res = Object.keys(alllinks).reduce((acc, elem)=>{
  return {
    first : alllinks[elem].first,
    last : alllinks[elem].last
  };
},{});

This is how i get data from firebase

get(child(dbRef, `links/${dummy.prefix}/links/links`)).then((snapshot) => {
  if (snapshot.exists()) {
    const dummy = snapshot.val();
    setAlllinks(dummy)
  } else {
    console.log("No data available");
  }
}).catch((error) => {
  console.error(error);
});

2

Answers


  1. You could assign your object with index like keys to an array.

    console.log(Object.assign([], { 0: 'foo', 1: 'bar' }));
    Login or Signup to reply.
  2. Try this maybe:

    var res = Object.keys(alllinks).reduce((acc, elem)=>{
      return {
        first : alllinks[elem].first,
        last : alllinks[elem].last
      };
    }, []); // changed to empty array
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search