How to convert a nested string of array to array

I have an array of objects in my state called ‘posts’. Each object in the array has a property called ‘amenities’, and that property is a stringed array. I’m trying to map through posts, and within the function map through the amenities of each post
Will this is not really the major problem here, the major problem here is when I receive amenities from DB it was wrapped in a string amenities: "["Security","Electricity","Water Supply"]". How do I convert this string to its original array so I can map through?

image

Basically you can use the always reliable

JSON.parse('stringified object');
1 Like

Thanks, very much this works

sir quick question: how do i get only one item from an array when mapping

If it’s always one item, then it shouldn’t be in an array.

If it’s a specific item, then you’ll have to tell us which one.

images: [{"imgUri":"osbook2020-08bd5577-cc3e-4398-8ff8-7a132f87d39c1589995847186.jpg", {"imgUri":"osbook2020-08bd5507-cc3e-4398-8ff8-7a132f87d39c1589967657122.jpg"}] so I have an array of images but I only wanna map out the first image in the array to display as cover

That array has an error in it. It’s missing a }.

In any event…

const [ cover ] = JSON.parse(your_json_str)

Then you use cover.img for the value of the image.

1 Like

yeah i noticed the missing }

ive solved this issue, inside of the posts.map function i did this
const aminities = JSON.parse(post.aminities)

                const aminities = JSON.parse(post.aminities)
                const imgs = JSON.parse(post.images)
                const imgsLength = imgs.length

                    const images = imgs.slice(0, imgsLength).map((img) => {
                    const cover = `images/${img.imgUri}`
                    return(
                        <img src={cover} />
                    )
                })
1 Like

Mapping a singleton is pointless in this situation; you can just grab it and use its value or transform it as you wish. There are infinite ways to grab it:

  • Via index
  • Pattern-Matching/Destructuring
  • Using a helper function

The safest way would be one of the first two but making sure you have a fallback:

// 1) Index
const coverImg = parsedJSONArray[0] || 'fallback.jpg');
// 2) Destructuring
const [coverImg] = parsedJSONArray;
// 2.1) When about to use it:
coverImg || 'fallback.jpg'

Both ways will yield undefined if the array is empty, which is the most harmless error you can expect. But what if the parsed object isn’t an array at all but rather a primitive, null, undefined, a JSON object, or worse; what if an exception happens? Handling objects that are fetched over the network must be thought with calm and you must have always have a fallback to show the user what went wrong.

2 Likes