userlkjsflkdsvm
userlkjsflkdsvm

Reputation: 983

Combine Objects and place into array - JavaScript / React

I have multiple objects in an array. They each have a labelId assigned to them. If the label id is the same then I need to combine the objects by placing some of the values inside an array of the new combined object.

[
    {
        field: "legalName",
        isOpened: false,
        label: "Legal Name",
        labelId: 1,
        value: "John Doe"
    },
    {
        field: "homeAddress1",
        isOpened: false,
        label: "Home Address",
        labelId: 2,
        value: "2343 Main Street"
    },
    {
        field: "homeAddress2",
        isOpened: false,
        label: "Home Address",
        labelId: 2,
        value: "New York, NY"
    }
]

What I want it to look like

[
    {
        isOpened: false,
        label: "Legal Name",
        labelId: 1,
        values:
            [
                {field: "legalName", value: "John Doe"}
            ]
    },
    {
        isOpened: false,
        label: "Home Address",
        labelId: 2,
        values:
            [
                {field: "homeAddress1", value: "2343 Main Street"},
                {field: "homeAddress2", value: "New York, NY"}
            ]
    }
]

I am removing the field and value from the original object and placing it into an array of values for all objects regardless if they have the same labelId.

Code so far -

personalInfoArray.forEach(info => {
    personalInfoArray.forEach(info2 => {
        if ((info.labelId === info2.labelId) && (info.field !== info2.field)) {
            info.values = [
                {field: info.field, value: info.value},
                {field: info2.field, value: info2.value}
            ]

        }
    })
})

I am looping through the same array twice in order to determine if the object has the same labelId, if success - create array. The issue is I'm not removing the properties and the other object still exists. Along with if they don't have the same labelId, nothing happens.

Thanks

Upvotes: 1

Views: 222

Answers (1)

Ele
Ele

Reputation: 33736

This is an approach using the function Array.prototype.reduce to group the object by labelId and the function Object.values to extract the grouped objects.

let arr = [{    field: "legalName",    isOpened: false,    label: "Legal Name",    labelId: 1,    value: "John Doe"  },  {    field: "homeAddress1",    isOpened: false,    label: "Home Address",    labelId: 2,    value: "2343 Main Street"  },  {    field: "homeAddress2",    isOpened: false,    label: "Home Address",    labelId: 2,    value: "New York, NY"  }],
    result = Object.values(arr.reduce((a, {labelId, field, isOpened, label, value}) => {
      (a[labelId] || (a[labelId] = {isOpened, label, labelId, values: []})).values.push({field, value});
      return a;
    }, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions