Home > Enterprise >  jquery object, merge duplicate value as array
jquery object, merge duplicate value as array

Time:08-04

I have an array of object with duplicate name object (here "Letter"). I need to merge objects named "Letter" as an array of the Values.

How can I manage it with jquery ?

FYI, the object come from a form "$(form).serializeArray()" with mutiple option in select

Original :

[
    {
        "name": "Hello",
        "value": "World"
    },
    {
        "name": "Letter",
        "value": "A"
    },
    {
        "name": "Letter",
        "value": "B"
    }
]

Expected :

[
    {
        "name": "Hello",
        "value": "World"
    },
    {
        "name": "Letter",
        "value": [
            "A",
            "B"
        ]
    }
]

CodePudding user response:

I think this is what your after

var data = [
    {
        "name": "Hello",
        "value": "World"
    },
    {
        "name": "Letter",
        "value": "A"
    },
    {
        "name": "Letter",
        "value": "B"
    }
];

const result = Array.from(new Set(data.map(s => s.name)))
    .map(item => {
      return {
        name: item,
        value: data.filter(s => s.name === item).map(x => x.value)
      }
    })

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I hope this helps

CodePudding user response:

here is a minor tweek for you

var data = [{
    "name": "Hello",
    "value": "World"
  },
  {
    "name": "Letter",
    "value": "A"
  },
  {
    "name": "Letter",
    "value": "B"
  }
];

const result = Array.from(new Set(data.map(s => s.name)))
  .map(item => {
    return {
      name: item,
      value: data.filter(s => s.name === item).map(x => x.value).length === 1 ? data.filter(s => s.name === item).map(x => x.value)[0] : data.filter(s => s.name === item).map(x => x.value)
    }
  })

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Is this better ?

  • Related