0

I have amended a firebase structure from an array

{
   "posts" : [
   {
      "code" : "BAcyDyQwcXX",
      "caption" : "Lunch #hamont",
      "likes" : 56,
      "id" : "1161022966406956503",
      "display_src" : "https://test1.jpg"
   },
   {
      "code" : "BAcJeJrQca9",
      "caption" : "Snow! ⛄️🌨❄️ #lifewithsnickers",
      "likes" : 59,
      "id" : "1160844458347054781",
      "display_src" : "https://test2.jpg"
   },
   ]
}

to a 'flattened' object

{
    "posts" : {
        "1161022966406956503" : {
            "code" : "BAcyDyQwcXX",
            "caption" : "Lunch #hamont",
            "likes" : 56,
            "display_src" : "https://test1.jpg"
        },
        "1160844458347054781" : {
            "code" : "BAcJeJrQca9",
            "caption" : "Snow! ⛄️🌨❄️ #lifewithsnickers",
            "likes" : 59,
            "display_src" : "https://test2.jpg"
        }
    }
}

and now wish to refactor the following code to accommodate for the handling of an firebase object instead of an array:

 const { postId }  = this.props.params;
 const i = this.props.posts.findIndex((post) => post.code === postId);

How do I do this?

1 Answer 1

1

There is no findIndex method, since you don't have an array anymore.

To find the key of the value, you'd use:

const posts = this.props.posts;
const key = Object.keys(posts).find((prop) => posts[prop].code === postId);

But why are you storing the posts under a timestamp when they already have a valid key? I'd recommend storing each post under that key:

{
    "posts" : {
        "BAcyDyQwcXX" : {
            "caption" : "Lunch #hamont",
            "likes" : 56,
            "display_src" : "https://test1.jpg"
        },
        "BAcJeJrQca9" : {
            "caption" : "Snow! ⛄️🌨❄️ #lifewithsnickers",
            "likes" : 59,
            "display_src" : "https://test2.jpg"
        }
    }
}

Then you no longer need to lookup the index/key for a post, since you already have the key that you store it under.

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

1 Comment

Many thanks, @Frank. Your recommendations have been noted and adopted

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.