Home > OS >  How to add an element to the beginning when building a map()
How to add an element to the beginning when building a map()

Time:09-05

enum StatusEnum {
  accepted = "AC",
  rejected = "RJ",
}
const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({
  value: x,
  name: x   "_random",
}))
/**
 * Console.log(select)
 * [
 * 0: { value: "accepted" , name: "accepted_random" }
 * 1: { value: "rejected" , name: "rejected_random" }
 * ]
 */

How to beautifully add an object to the beginning of an array { value: "all" , name: "all_random" } ?

/**
 * Console.log(select)
 * [
 * 0: { value: "all" , name: "all_random" }
 * 1: { value: "accepted" , name: "accepted_random" }
 * 2: { value: "rejected" , name: "rejected_random" }
 * ]
 */

CodePudding user response:

Surround it with an array and add the item at the beginning with spread operator for the map function.

const select = [{ value: "all" , name: "all_random" }, ...(Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({
  value: x,
  name: x   "_random",
}))]

  • Related