1

How can I get the values of the products array inside of an array. I want to combine the products array?

data = [
    {
        "id": "ORDER-111",
        "products": [
            {
                "id": "5435",
                "productName": "Banana",
            }
        ],
    },
    {
        "id": "ORDER-222",
        "products": [
            {
                "id": "75434",
                "productName": "Apple",
            },
             {
                "id": "5345",
                "productName": "Mango",
            }
        ],
    }
]

EXPECTED OUTPUT

"products": [
            {
                "id": "5435",
                "productName": "Banana",
            },
            {
                "id": "75434",
                "productName": "Apple",
            },
             {
                "id": "5345",
                "productName": "Mango",
            }
        ],

CODE

console.log(
  ...data
    .reduce((r, { products }) => {
      (products || []).forEach((o) => {
        r.has(o.id);
      });

      return r;
    }, new Map())
    .values()
);
1
  • @CertainPerformance. Edited my question. Please check again Commented Mar 11, 2021 at 3:55

1 Answer 1

1

This would be a good place to use .flatMap - in the callback, just navigate to the products subarray of each object:

const data = [
    {
        "id": "ORDER-111",
        "products": [
            {
                "id": "5435",
                "productName": "Banana",
            }
        ],
    },
    {
        "id": "ORDER-222",
        "products": [
            {
                "id": "75434",
                "productName": "Apple",
            },
             {
                "id": "5345",
                "productName": "Mango",
            }
        ],
    }
];
const result = data.flatMap(obj => obj.products);
console.log(result);

In older environments without flatMap, use a polyfill or spread into concat instead:

const data = [
    {
        "id": "ORDER-111",
        "products": [
            {
                "id": "5435",
                "productName": "Banana",
            }
        ],
    },
    {
        "id": "ORDER-222",
        "products": [
            {
                "id": "75434",
                "productName": "Apple",
            },
             {
                "id": "5345",
                "productName": "Mango",
            }
        ],
    }
];
const result = [].concat(...data.map(obj => obj.products));
console.log(result);

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

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.