Search code examples
javascriptarraysjsonobject

Merge two name value pairs in an object


Is it possible to merge two name value pairs into one in an object? Can it be done by a foreach or something? I have seen examples of merging two objects to one but not merging name value pairs within an object of an array.

Original array:

[
    {
        "id": "10bf820c19869d1097b0f056c924d9f8",
        "text1": "Text A",
        "text2": "Option"
    },
    {
        "id": "7b6a8f291986955097b0f056c924d981",
        "text1": "Text B",
        "text2": "Option"
    },
    {
        "id": "99ca5a64b45a551097b07caca12ca710",
        "text1": "Text C",
        "text2": "Option"
    }
]

To be:

[
    {
        "id": "10bf820c19869d1097b0f056c924d9f8",
        "text": "Text A - Option"
    },
    {
        "id": "7b6a8f291986955097b0f056c924d981",
        "text": "Text B - Option"
    },
    {
        "id": "99ca5a64b45a551097b07caca12ca710",
        "text": "Text A - Option"
    }
]

Solution

  • You can use map() to do it

    let data = [
        {
            "id": "10bf820c19869d1097b0f056c924d9f8",
            "text1": "Text A",
            "text2": "Option"
        },
        {
            "id": "7b6a8f291986955097b0f056c924d981",
            "text1": "Text B",
            "text2": "Option"
        },
        {
            "id": "99ca5a64b45a551097b07caca12ca710",
            "text1": "Text C",
            "text2": "Option"
        }
    ]
    
    let result = data.map(d => ({'id':d.id,'text':d.text1 + ' - ' + d.text2}))
    console.log(result)