Home > Software engineering >  Flatten an array in most efficient manner
Flatten an array in most efficient manner

Time:05-28

I would like to do something like this but in a more large scale and efficient way. Assume I have the array of objects to be flattened.

Convert:

{
  name: 'john doe',
  address: { apartment: 1550, streetno: 167, streetname: 'Victoria', a... }
  b...
}

to this -

{
  name: 'john doe',
  apartment: 1550,
  streetno: 167,
  streetname: 'Victoria'
  a...
  b...
}

Using js methods.

CodePudding user response:

Assuming you have an array of these objects, you can easily combine each object with its "address" property using destructuring:

const myInput = [
  {
    name: 'john doe',
    address: { apartment: 1550, streetno: 167, streetname: 'Victoria'}
  },
  {
    name: 'Joe Smith',
    address: { apartment: 2, streetno: 111, streetname: 'Jones'}
  }
];

const myOutput = myInput.map(({address, ...rest}) => ({...rest, ...address}));
console.log(myOutput);

CodePudding user response:

map over the array and return a new object that has had its address property merged into it, the address property deleted, and the new object returned.

const arr=[{name:"john doe",address:{apartment:1550,streetno:167,streetname:"Victoria",a:"a"},b:"b"}];

const out = arr.map(obj => {
  const newObj = { ...obj, ...obj.address };
  delete newObj.address;
  return newObj;
});

console.log(out);

CodePudding user response:

That isn't an array.

If you want to flatten a dictionary, do it this way: https://stackoverflow.com/a/22047469/5676613

This has O(n^k) and Omega(n) time complexity where n is the size of the dictionary, and k is the depth of the dictionary (or how many nests are in the dictionary).

  • Related