Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping object to array

Given an object like this:

{
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
...
}

What is the simplest way to return this array:

[
   {value: "aaa", label: "Text1"},
   {value: "bbb", label: "Text2"}
]

Do I have to loop through the object? I thought there might be a way with Object.keys() and Object.values()

like image 643
Dan Avatar asked Jun 14 '26 12:06

Dan


1 Answers

You can use Object.entries to convert the object into an array. Use map to loop and return the desired object.

let obj = {
  aaa: {
    text: "Text1",
    path: "Path1",
    type: "Type1"
  },
  bbb: {
    text: "Text2",
    path: "Path2",
    type: "Type2"
  },
}

let result = Object.entries(obj).map(([k, v]) => ({value: k,label: v.text}));

console.log(result);
like image 189
Eddie Avatar answered Jun 17 '26 01:06

Eddie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!