Get Values Array Inside Array in ES6

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()
);

Answer

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);

Leave a Reply

Your email address will not be published. Required fields are marked *