Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to flattern the array of object in javascript

I am trying flattern the array of object . I am able to do that . I just want to know is it correct way to do that or is there any better library available ?

Data

const data = {
      details: [
        {
          item_details: {
            number: "sdas",
            date: "28/07/2022"
          }
        },
        {
          item_details: {
            number: "hello",
            date: "28/07/2022"
          }
        }
      ]
    };

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function convetObj(data) {
  let res = {};
  for (let i = 0; i < data.details.length; i++) {
    res[`details[${i}].item_details.number`] =
      data.details[i].item_details.number;
    res[`details[${i}].item_details.date`] = data.details[i].item_details.date;
  }
  return res;
}

console.log(convetObj(data));

Here is my code at CodeSandbox

I am getting same as expected output, but wanted to know is it better way ? any better library available

expected output

{
  details[0].item_details.number:"sdas",
  details[0].item_details.date:"28/07/2022"
  details[1].item_details.number:"hello",
  details[1].item_details.date:"28/07/2022"
}

actual output

{
 "details[0].item_details.number": "sdas",
 "details[0].item_details.date": "28/07/2022",
 "details[1].item_details.number": "hello",
 "details[1].item_details.date": "28/07/2022"
} 

>Solution :

With recursion you can flatten an object of any structure, so it’s generic, can be reused on any object, seems better than flatten object every time manually:

const flatten = (obj, target = {}, path = '') => {
  if(Array.isArray(obj)){
    for(let i = 0; i< obj.length; i++){
      flatten(obj[i], target, `${path}[${i}]`);
    }
  }else if(obj.__proto__ === Object.prototype){
    for(const key in obj){
      flatten(obj[key], target, `${path}${path ? '.' : ''}${key}`);
    }
  }else{
     target[path] = obj;
  }
  
  return target;
};

console.log(flatten(data));
<script>
const data = {
      details: [
        {
          item_details: {
            number: "sdas",
            date: "28/07/2022"
          }
        },
        {
          item_details: {
            number: "hello",
            date: "28/07/2022"
          }
        }
      ]
    };

</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading