-2

I have this array and I want to console log item value. How can I do that? I got this array from MongoDB. I would appreciate any help.

{
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}

Edit: I looked in MongoDB documentation and found the solution. Thanks to everyone who answered.

1
  • 1
    What have you tried? What was the result? Why did the result not satisfy your requirements? What have you tried to solve that problem? Sep 19, 2021 at 9:45

2 Answers 2

3

I think you can simply access the key from the object like this:

const obj = {
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}

console.log(obj.item);

Another way could be to find out the keys and iterate over them if keys are dynamic in nature:

const obj = {
"_id" : "61462a7bf3c0be993bcfdc3e",
"item": "journal",
"qty": 25,
"size": {
"h": 14,
"w": 21,
"uom": "cm"
},
"status": "A"
}

const keys = Object.keys(obj);

keys.forEach(key => console.log(`Key is ${key} and the value is ${JSON.stringify(obj[key])}`))

4
  • There's no need to use optional chaining in that first example because you know obj exists.
    – Andy
    Sep 19, 2021 at 10:25
  • The user didn't specify any schema which says the item will always exist. So, I thought to include it tho it is not needed if it does. Sep 19, 2021 at 10:28
  • 1
    But that checks for the existence of obj, and you already know it exists because you defined it.
    – Andy
    Sep 19, 2021 at 10:30
  • 1
    made the change, thank you for correction. Sep 19, 2021 at 10:33
1

You can try:

Object.entries(YOUR_OBJECT_NAME).filter(val=>val[0] === "item")

You will get back an array of key and value pair. You can then console.log your value.

Easier solution is that you directly determine your key. If you know what is the name of your key then you can do:

console.log(YOUR_OBJECT_NAME.item)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.