Home > Back-end >  How to I remove duplicates and append multi layer JSON array?
How to I remove duplicates and append multi layer JSON array?

Time:07-09

I have an array which has different location and items.

[
    {"location": "north", "items" : ["IT1", "IT2"]},
    {"location": "south", "items" : ["IT1", "IT2"]},
    {"location": "north", "items" : ["IT3", "IT4"]}
]

I want to remove duplicate location fields and append the items property from the duplicate to achieve this:

[
    {"location": "north", "items" : ["IT1", "IT2", "IT3", "IT4"]},
    {"location": "south", "items" : ["IT1", "IT2"]}
]

How can I do it with vanilla JS?

CodePudding user response:

I hope it would work for you


var data = [
    {"location": "north", "items" : ["IT1", "IT2"]},
    {"location": "south", "items" : ["IT1", "IT2"]},
    {"location": "north", "items" : ["IT3", "IT4"]}
];

const result = data.filter((thing, index, self) =>
  index === self.findIndex((t) => (
    t.location === thing.location
  ))
)
console.log(result);

CodePudding user response:

By adapting How to group or merge this array of objects in javascript? to accumulate arrays instead of numbers, here's the result:

var arr = [{
    "location": "north",
    "items": ["IT1", "IT2"]
  },
  {
    "location": "south",
    "items": ["IT1", "IT2"]
  },
  {
    "location": "north",
    "items": ["IT3", "IT4"]
  }
];

var finalArr = arr.reduce((m, o) => {
  var found = m.find(p => p.location === o.location);
  if (found) {
    found.items = found.items.concat(o.items);
  } else {
    m.push(o);
  }
  return m;
}, []);

console.log(finalArr)

  • Related