Shiv
Shiv

Reputation: 23

fetch json value using Object.values in node js / Javascript

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

Answers (2)

Nikolay
Nikolay

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

Tej
Tej

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

  1. First we will check if description itself is present and retrieve its key or default it to empty string
  2. Then we will check if key is not empty string and then retrieve the value using the key.
  3. 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)
 }
})

Upvotes: 1

Related Questions