Home > Blockchain >  convert object keys and values in single Array JS?
convert object keys and values in single Array JS?

Time:04-09

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"},
    { Name:"Tom",Age:29,"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

CodePudding user response:

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

CodePudding user response:

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

  • Related