I am trying to fetch data from the JSON object by using Object.values
so my JSON looks like this
const jsonValue=
[
{
files:{
title:{
"en": "test"
}
,
description:{
"en": "dummy description"
}
}
},
{
files:{
title:{
"eu": "without description"
}
}
},
];
jsonValue.map((data)=>{
const des =Object.values(Object.values(data)[0]?.description)?? "";
console.log(...des)
})
I am trying to fetch the description value and if the description key is not present then it should return a blank space
I am using Object.values because en, and eu values get changed every time so to overcome this I am using Object.values
but it showing me an error cannot convert undefined.
My expected output is I want to fetch the description value if it presents inside the JSON and return a blank space if it is not present in JSON
-
How to debug small programs and What is a debugger and how can it help me diagnose problems?VLAZ– VLAZ2023年01月24日 11:14:42 +00:00Commented Jan 24, 2023 at 11:14
-
There's no JSON in your codeQuentin– Quentin2023年01月24日 11:35:36 +00:00Commented Jan 24, 2023 at 11:35
2 Answers 2
Your solution is almost correct and I just did a small modification at the end to make it work as per the requirement.
This is how it works
- First we will check if description itself is present and retrieve its key or default it to empty string
- Then we will check if key is not empty string and then retrieve the value using the key.
- Display the required result.
I just added a bit more console logs to show how each step behaves and these are not needed as part of solution.
Like VLAZ suggested it is always handy to use browser debugger tools to see the failed statements.
const jsonValue=
[
{
files:{
title:{
"en": "test"
}
,
description:{
"en": "dummy description"
}
}
},
{
files:{
title:{
"eu": "without description"
}
}
},
];
jsonValue.map((data)=>{
console.log(Object.values(data)[0]?.description);
const desKey = Object.values(data)[0]?.description ?? "";
if(desKey !== ""){
console.log(Object.values(desKey));
const des = Object.values(desKey);
console.log(...des)
}
})
Comments
If I understood you correctly, when
const descriptions = jsonValue.map(value =>
value.files.description ?
value.files.description[Object.keys(value.files.title)[0]] :
''
)
console.log(descriptions)
will print ["dummy description", ""] and should do the trock
1 Comment
value.files.description[Object.keys(value.files.title)[0]] over Object.values(value.files.description)[0]? And why use The key from value.files.title rather than the one from .description?