'convert object keys and values in single Array JS?

I have an object that looks like this:

const dataObj =
{"Tom-29":[ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
]}

I want something like below and result sorted by number

[
   Name:"Tom",
   Age:29,
    [{"number": 12, "string": "hi"},
    {"number": 40, "string": "bye"}]
];

How would i do this ? I tried below approach .

 const arr =Object.entries(dataObj).map(itm=>({...itm,Name:itm[0]}));

Please help me to resolve



Solution 1:[1]

You can use the object key and append it to each of it's children as a name.

    const dataObj =
    {"Tom-29":[ 
        { "number": 12, "string": "hi"},
        { "number": 40, "string": "bye"}
    ]}

    const results = Object
      .keys(dataObj)
      .map(k => { 
        dataObj[k].forEach(i => { 
          i.name = k.split('-')[0]; 
          i.age = k.split('-')[1]; 
        }); 
        return dataObj[k] 
      })
      .flat();

    console.log(results);

Solution 2:[2]

Iterate the dataObj entries with Array.flatMap(), extract the name and age from the key, and then map the values, and add the properties to the original object using array spread:

const dataObj = {"Tom-29":[{"number":12,"string":"hi"},{"number":40,"string":"bye"}]}

const result = Object.entries(dataObj)
  .flatMap(([key, values]) => {
    const [name, age] = key.split('-')
    
    return values.map(v => ({
      name,
      age: +age,
      ...v
    }))
  })
  
console.log(result);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ori Drori