<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const secret = [
{key:'1'},
{key:'2'}
];
document.getElementById("demo").innerHTML = secret.filter((value)=>{return value.key>1});
</script>
</body>
</html>
I am expecting output should be the second object in the array as key:2. Which part I am trying is wrong.As I am getting output as [object Object]
4
Answers
you are getting the second entry, but you are sending it to the DOM and it’s serialising it as
[object Object]
to tell you that you have an object of type object. You can make it JSON, and then print it by wrapping the statement inJSON.stringify()
. That will print out[{"key":"2"}]
instead of[object Object]
If you try
in the console you’ll see the
.filter
call is returning an array:But whether you get an array
[...]
or an object{...}
, when you’re assigning it as the value to innerHTML, it’s becoming casted as a string. e.g., it’s doing,String( [{key:"2"}] )
.And if you try
console.log(String( [] ))
orconsole.log(String( {} ))
you’ll see that both yield the"[object Object]"
that you’re seeing.If you want it to print the object construct, you’ll want to convert it to JSON. e.g.:
yields
"[{key:"2"}]"
If you want just the object, you may want to try the
.find
function instead:yields
"{key:"2"}"
this part of the code
returns an array because it filters all the items in the original array (called secret in this case) and selects all the elements respecting the condition (>1 in this case).
if you’re sure just one item is the one you need, just add [0] and the key at the end:
or you could use a cycle to get all the values selected
something like this should fix your problem!
i would personally use the last fix… it’s more scalable
hope this helps