Javascript 在nodejs中将Json对象转换为数组
下面我将上述yaml文件转换为JSON对象,并尝试根据id查找照片:Javascript 在nodejs中将Json对象转换为数组,javascript,node.js,yaml,Javascript,Node.js,Yaml,下面我将上述yaml文件转换为JSON对象,并尝试根据id查找照片: Photos: - id: Photo1 Type: Color Shade: Grey - id: Photo2 Type: Color Shade: Red 以下结果是在以下条件下获得的: const raw = fs.readFileSync("Photos.yaml", 'utf8'); const Phot
Photos:
- id: Photo1
Type: Color
Shade: Grey
- id: Photo2
Type: Color
Shade: Red
以下结果是在以下条件下获得的:
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 );
}
问题:我怀疑在console.log(photoArray)的结果中获取“照片”导致我基于id搜索照片失败。如何删除这个?我相信,如果删除此项,搜索和返回照片将有效您的数据位于de
Photos
对象中,然后您将推入一个空数组。
因此,当您从数组中查找时,需要从正确的位置获取它
正确代码:
(功能测试(id){
let PhotoData=“{\'Photos\”:[{\'id\':\'Photo1\,\'Type\':\'Color\,\'Shade\':\'Grey\,{\'id\':\'Photo2\,\'Type\':\'Color\,\'Shade\':'Red\'}”
让photoArray=[];//photoArray
让getPhoto=JSON.parse(PhotoData);//转换为JSON对象
console.log(getPhoto);
photoArray.push(getPhoto);//推送到arrayv以便进行搜索
console.log(photoArray);
const foundPhoto=photoArray[0]。Photos.find((photo)=>photo.id==id);
console.log(foundPhoto);
})(“照片1”)
奇怪的是,您将这个带有照片的对象转换回带有JSON.stringify()
的字符串,然后将该字符串添加到数组中。见下面我的建议
const existingArrayOfPhotos=[];
yamlString=`照片:
-id:Photo1
类型:彩色
色调:灰色
-id:Photo2
类型:彩色
颜色:红色`
常量photoData=YAML.parse(yamlString);
现有ArrayOfPhotos.push(…photoData.Photos)
const foundPhoto=existingArrayOfPhotos.find((photo)=>photo.id==“Photo1”);
console.log(foundPhoto)代码>
您正在推的getLayout
不应该是getPhoto
?另外,stringify
将对象转换为json字符串,而不是对象。。您需要JSON.parse()
该字符串。是的,在堆栈溢出时将其写入此处是一个错误。已更正,此处似乎存在断开连接photoArray
打印一个对象,但是code中没有任何地方将photoArray
从一个数组重新分配到一个对象,JSON.stringify()
,正如名称所示,返回一个字符串。更正了它@Andreashis对我有效。谢谢
console.log(photoArray) => {"Photos":[{"id":"Photo1","Type":"Color","Shade":"Grey"},{"id":"Photo2","Type":"Color","Shade":"Red"}]}
console.log(foundPhoto) => undefined