Home > Mobile >  a better way to map a list in js
a better way to map a list in js

Time:12-27

I often use map() when repeating the same format of content.

At this time, the list is made as follows.

A.

const list = [{title: a, content: 1}, {title: b, content: 2}, {title: c, content: 3}]

list.map((item) => (
 <div>
  <div>{item.title}</div>
  <div>{item.content}</div>
 </div>
))

B.

const list = {a: 1, b: 2, c: 3}

Object.keys(list).map((item) => (
 <div>
  <div>{item}</div>
  <div>{list[item]}</div>
 </div>
))

When I make a list, I often use B, bacause I like to classify the content into the key of object.

Is there any disadvantage in performance in using B?

I don't know how to find the answer, so I'm gonna post it here.

CodePudding user response:

A couple problems with using variable object keys (such as the title, in your question) are:

  • If the title/key varies and is dynamic (which I'd think would be pretty likely, given how programmers like to make things DRY and automated), you'll have to be sure that the key names and values always come from trustworthy sources. Otherwise - like if the values could come from user input or an API or something - you could be opening yourself up to malicious code execution in some circumstances. It's not a very uncommon problem.

    This is one of the reasons Maps are often the better choice when dealing with dynamic "keys" - they don't have such problems. (Or, don't use dynamic keys at all)

  • V8, at least, utilizes hidden classes to optimize the internal object structures held by the interpreter. This works well when there are objects which all have the same property names, but doesn't work when the properties are all dynamic. It's exceedingly unlikely to be noticeable, but you might want to keep it in mind.

CodePudding user response:

There are 3 types to iterate over object.

  1. Object.keys()
  2. Object.values()
  3. Object.entries()

In your case, you can try Object.entries()

const list = {a: 1, b: 2, c: 3}

Object.entries(list).map(([key, value]) => (
 <div>
  <div>{key}</div>
  <div>{value}</div>
 </div>
))

For more ref: Object.entries

  • Related