Mr.Curious
Mr.Curious

Reputation: 292

Convert Json object to array in nodejs

 Photos:
      - id: Photo1
        Type: Color
        Shade: Grey
      - id: Photo2
        Type: Color
        Shade: Red

Here am converting the above yaml file to JSON Object and trying to find a photo based on id:

const raw = fs.readFileSync("Photos.yaml", 'utf8');
const PhotoData= YAML.load(raw);

export const getSpecificPhoto = (req,res)=>{
    const { id } = req.params;
    let photoArray = []; //photoArray
    let getPhoto = JSON.stringify(PhotoData);  //Converting to JSON string

    photoArray.push(getPhoto); //Pushing to arrayv so that search can be done
    console.log(photoArray);
    const foundPhoto = photoArray.find((photo) => photo.id == id);

    console.log(foundPhoto );
}

The following results are obtained on :

console.log(photoArray) => {"Photos":[{"id":"Photo1","Type":"Color","Shade":"Grey"},{"id":"Photo2","Type":"Color","Shade":"Red"}]}

console.log(foundPhoto) => undefined

Problem : I am suspecting that getting of "Photos": in result of console.log(photoArray) is causing my search of photo based on id to fail. How to remove this ? I believe if this gets removed searching and returning of photo will work

Upvotes: 1

Views: 2135

Answers (2)

JerMah
JerMah

Reputation: 763

It's strange that you convert this object with photos back to a string with JSON.stringify() and then add that string to an array. See my suggestion below.

const existingArrayOfPhotos = [];

yamlString = `Photos:
      - id: Photo1
        Type: Color
        Shade: Grey
      - id: Photo2
        Type: Color
        Shade: Red`
        
const photoData = YAML.parse(yamlString);
existingArrayOfPhotos.push(...photoData.Photos)
const foundPhoto = existingArrayOfPhotos.find((photo) => photo.id == "Photo1");

console.log(foundPhoto);
<script src="https://cdnjs.cloudflare.com/ajax/libs/yamljs/0.3.0/yaml.min.js"></script>

Upvotes: 1

shtse8
shtse8

Reputation: 1365

Your data is insode Photos object, and then you push in an empty array. So when you find from the array, you need to get it from the correct position.

Correct code:

(function test(id) {
let PhotoData = "{\"Photos\":[{\"id\":\"Photo1\", \"Type\": \"Color\", \"Shade\": \"Grey\"}, {\"id\": \"Photo2\", \"Type\": \"Color\", \"Shade\": \"Red\"}]}"
let photoArray = []; //photoArray
let getPhoto = JSON.parse(PhotoData);  //Converting to JSON object
console.log(getPhoto);
photoArray.push(getPhoto); //Pushing to arrayv so that search can be done
console.log(photoArray);
const foundPhoto = photoArray[0].Photos.find((photo) => photo.id == id);

console.log(foundPhoto );
})("Photo1");

Result:

{id: "Photo1", Type: "Color", Shade: "Grey"}

Upvotes: 2

Related Questions