Reputation: 23
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
Upvotes: 0
Views: 63
Reputation: 3828
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
Upvotes: 0
Reputation: 414
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
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)
}
})
Upvotes: 1