Home > Software design >  Javascript Array Formatting - Repeating Data
Javascript Array Formatting - Repeating Data

Time:03-27

I want to show the repeating building names as an array in the employee array below.

const employess = [
  {
    building_name: "A",
    name: "John"
  },
  {
    building_name: "B",
    name: "John"
  },
  {
    building_name: "A",
    name: "Doe"
  },
  {
    building_name: "c",
    name: "John"
  },
  {
    building_name: "B",
    name: "Doe"
  }, 
  {
    building_name: "C",
    name: "David"
  }
];

For example, I want to convert it to the following array format.

const employess = [
  {
    building_name: ["A", "B", "C"],
    name: "John"
  },
  {
    building_name: ["A", "B"],
    name: "Doe"
  },
  {
    building_name: ["C"],
    name: "David"
  }
]

Thank you very much in advance for your help.

CodePudding user response:

You might want to look at Array.prototype.reduce for that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce.

CodePudding user response:

Taken from Merge JavaScript objects in array with same key

const employess = [{
    building_name: "A",
    name: "John"
  },
  {
    building_name: "B",
    name: "John"
  },
  {
    building_name: "A",
    name: "Doe"
  },
  {
    building_name: "c",
    name: "John"
  },
  {
    building_name: "B",
    name: "Doe"
  },
  {
    building_name: "C",
    name: "David"
  }
]

let output = []

employess.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.name == item.name;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].building_name = output[existingIndex].building_name.concat(item.building_name);
  } else {
    if (typeof item.building_name == 'string')
      item.building_name = [item.building_name];
    output.push(item);
  }
});

console.log(output)

  • Related