Array to Array group convert

Viewed 57

I need to convert this array in JavaScript. I have tried many ways but not working...

value = [
  {
      group: "Switzerland",
      id: "A",
      name: "ABC"
  },
  {
      group: "Switzerland",
      id: "B",
      name: "ABC3"
  },
  {
      group: "France",
      id: "C",
      name: "ABC1"
  },
  {
      group: "Italy",
      id: "F",
      name: "ABC3"
  }
]

I need to convert the above array to the below array format.

value = [
  {
    name: 'Switzerland',
    bank: [
      {
        group: "Switzerland",
        id: "A",
        name: "ABC"
      },
      {
        group: "Switzerland",
        id: "B",
        name: "ABC3"
      }
    ]
  },
  {
    name: 'France',
    bank: [
      {
        group: "France",
        id: "C",
        name: "ABC1"
      }
    ]
  },
  {
    name: 'Italy',
    bank: [
      {
        group: "Italy",
        id: "F",
        name: "ABC3"
      }
    ]
  }
]
3 Answers

You can just iterate through the original objects and copy the values into a new object that corresponds to your new model.

let newArray = []

for (let item of value) {
    let newItem = {
        name: item.group,
        bank: [{
            group: item.group,
            id: item.id,
            name: item.name,
        }]
    }
    newArray.push(newItem)
}

(You should always include some explanation about what you were trying to achieve and what is the starting point of your code, but hope this helps.)

Go through the items, and build an object with key as group.
when same group item occur, aggregate the values.

const combine = (arr) => {
  const all = {};
  arr.forEach((item) => {
    if (!all[item.group]) {
      all[item.group] = {
        name: item.group,
        bank: [],
      };
    }
    all[item.group].bank.push({ ...item });
  });
  return Object.values(all);
};

value = [
  {
    group: "Switzerland",
    id: "A",
    name: "ABC",
  },
  {
    group: "Switzerland",
    id: "B",
    name: "ABC3",
  },
  {
    group: "France",
    id: "C",
    name: "ABC1",
  },
  {
    group: "Italy",
    id: "F",
    name: "ABC3",
  },
];

console.log(combine(value));

According to your sample

function format(data) {
  const arr = [];
  const temp = {};
  data.forEach((obj, index) => {
    const item = { name: obj.group, bank: [] };
    if (temp.hasOwnProperty(obj.group)) {
      arr[temp[obj.group]].bank.push(obj);
    } else {
      item.bank.push(obj);
      arr.push(item);
    }
    temp[obj.group] = index;
  });
  return arr;
}
console.log(format(value));

https://stackblitz.com/edit/js-etadh9

Related