mirage
mirage

Reputation: 21

Javascript: How to convert and map an object containing objects into an array?

In Javascript, how to map and convert this object:

  {
    0: {k1 : v1},
    2: {k2 : v2}
  }

to this array:

[
    {
        label: k1,
        value: v1
    },
    {
        label: k2,
        value: v2
    }
]

obs.: one-liners are nice, but all answers are welcome.

I couldn't get the desired result, but I have blindly followed formulas like:

const objectMap = (obj, fn) =>
  Object.fromEntries(
    Object.entries(obj).map(
      ([k, v], i) => [i, fn(v, k, i)]
    )
  )
const cfieldsFinal = objectMap(modcf, (k, v) => ({
  label: v,
  value: k
}))

and that's ALMOST what I need, except, it's still an object:

output => {0: {label: k1, value: v1}, 1: {label: k2, value:  v2}}

So, only a complete noob such as myself would get stuck on this part...

Upvotes: 0

Views: 249

Answers (2)

Ori Drori
Ori Drori

Reputation: 191916

You're very close, you just need to construct the object manually. Start by using Array.values() to convert data to an array. Iterate the array with Array.flatMap() to flatten the sub-arrays create by the internal map. Convert each object to an array of [key, value] pairs. Map each pair, and create an object.

const data = {0: { k1: 'v1' }, 2: { k2: 'v2' }}

const result = Object.values(data) // convert data to an array
  .flatMap(o => // map to a flattend array
    Object.entries(o) // get the entries of each object 
      .map(([label, value]) => ({ label, value })) // create a new object from each entry
  )
  
console.log(result)

Upvotes: 2

zero298
zero298

Reputation: 26867

const foo = {
  0: {
    k1: "v1"
  },
  2: {
    k2: "v2"
  }
};

/*
[
    {
        label: k1,
        value: v1
    },
    {
        label: k2,
        value: v2
    }
]
*/

const oe = Object.entries;
const bar = oe(foo).map(([k, v]) => {
  const [label, value] = oe(v)[0];
  return {
    label,
    value
  };
});

console.log(bar);

Upvotes: 0

Related Questions