1

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

2 Answers 2

2

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

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

6 Comments

Name and age need to separated
I've updated that for you.
@Pellay one-liners are mostly unreadable. Could you separate it out a bit?
@Andy of course. It kind of grew a little. :)
@Pellay Sorry i have printed wrong format of result.I have edited my results.please help me\
|
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);

1 Comment

Sorry i have printed wrong format of result.I have edited my results.please help m

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.