1

I have an array of objects, each containing arrays and I want to merge them if each array contains display: true. I'm very new to array manipulation, and a nudge in the correct way would be very much appreciated.

Example array:

{
    "first": [
        {
            "name": "John",
            "surname": "Doe",
            "display": true
        },
        {
            "name": "Jane",
            "surname": "Doe",
            "display": false
        }
    ],
    "second": [
        {
            "name": "Sarah",
            "surname": "Doe",
            "display": true
        }
    ]
}

Example of expected result:

[
    {
        "name": "John",
        "surname": "Doe",
        "display": true
    },
    {
        "name": "Sarah",
        "surname": "Doe",
        "display": true
    }
]

I already have javascript code to set each display key to true/false based on search query. I just need the array merged to match the expected result.

2 Answers 2

2

You could get all values and filter the flat array.

const
    data = { first: [{ name: "John", surname: "Doe", display: true }, { name: "Jane", surname: "Doe", display: false }], second: [{ name: "Sarah", surname: "Doe", display: true }] },
    result = Object
        .values(data)
        .flat()
        .filter(({ display }) => display);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

Use a reducer and filter the values within on the display property value. Finally flatten the result:

const mergedByDisplay = Object.entries({
    "first": [{
        "name": "John",
        "surname": "Doe",
        "display": true
      },
      {
        "name": "Jane",
        "surname": "Doe",
        "display": false
      }
    ],
    "second": [{
      "name": "Sarah",
      "surname": "Doe",
      "display": true
    }]
  })
  .reduce((acc, [_, val]) => [...acc, val.filter(v => v.display)], [])
  .flat();
console.log(mergedByDisplay);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.