0

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...

0

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you both, Ori and zero298. No wonder I couldn't simply have deduced a way to do something apparently so trivial...
You're welcome. Don't be afraid to ask/answer. Some things that seem trivial now, took time to learn and evolve.
0

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);

Comments

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.