1

I have an array of objects. Is it possible to print key values using array.map method?

<div> +
array.map( x => {
return `<span class="key">"value"</span><br>
}) +
</div>
2
  • 1
    Why not using entries(), keys() & values()? Commented Aug 8, 2021 at 19:10
  • Do you mean every key and every value of an object? Commented Aug 8, 2021 at 19:11

2 Answers 2

1

Try mapping through Object.keys() of every object in the array this way

<div>
  array.map( obj => {
    return obj.keys().map( key => {
      return `<span class="${key}">${obj[key]}</span><br>`
    )}
  })
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this:

const array = [{
  key: '1',
  value: 'value-1'
}, {
  key: '2',
  value: 'value-2'
}];
const text = array.map(x => `<span class="${x.key}">${x.value}</span><br>`).join("");
const element = document.querySelector('#log');
element.innerHTML = text;
<div id="log"></div>

5 Comments

wdym by "If your objects have key and value"? Doesn't objects have key value bu default?
Objects can be empty, can have only key, whatever. Or I don't get the question right.
@AmirrezaAmini if you want to iterate through the object, like through the dictionary, then Object.entries should be the right choice
Yea I think you misunderstood it. He has definitely entries. Despite I told him, he can use entries, keys & values.
Ill check tomorrow, in case- will delete the answer :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.