skip to Main Content

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"
        ]
    }
]

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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 ?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search