Here is my Input Could you all help me out to get the all object based on values as list
{
Jack: 2,
olive: 1,
harry: 2
}
Want my output to be
harry = 2
olive = 1
jack = 2
Let me know if there is a way to get the output as mentioned above in javascript
-
By mentioning list u need to print as html?Sharoon Ck– Sharoon Ck2021年08月23日 04:28:46 +00:00Commented Aug 23, 2021 at 4:28
-
Or u just need to console.log it?Sharoon Ck– Sharoon Ck2021年08月23日 04:29:15 +00:00Commented Aug 23, 2021 at 4:29
-
why this strange order ?Mister Jojo– Mister Jojo2021年08月23日 04:32:15 +00:00Commented Aug 23, 2021 at 4:32
4 Answers 4
You can use the function Object.entries(object) and loop over all the entries to log the information how you want.
For more information on Object.entries(object) visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
const data = {
Jack: 2,
olive: 1,
harry: 2
};
const entries = Object.entries(data);
entries.forEach(([key, value]) => console.log(`${key} = ${value}`));
Comments
You could try the following:
const result = Object.entries(theObject).map(([key, value]) => `${key.toLowerCase((} = ${value}`).join(‘\n’);
console.log(result);
Hopefully that helps!
Comments
Please check Object.entries() or Object.keys().
Object.entries():- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
Object.keys():- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Comments
I know I'm probably not answering the question but, this just shows it in the DOM instead of the console.
If you want an ordered list just change the <ul> (opening and closing tags) to <ol>
<!DOCTYPE html>
<head>
<title>Document</title>
</head>
<body>
<div class="output"></div>
<script>
const data = {
Jack: 2,
Olive: 1,
Harry: 2
};
const entries = Object.entries(data);
let output = '<h1> Output </h1>';
entries.forEach(([key, value]) => {
output += `<ul>
<li> ${key} = ${value} </li>
</ul>`;
document.querySelector('.output').innerHTML = output;
});
</script>
</body>
</html>