Home > Software engineering >  Return multiple arrays of flat data while running Map on object array
Return multiple arrays of flat data while running Map on object array

Time:12-14

I am trying to extract multiple flat arrays of values from an object array.

I'm able to extract the values needed using ES6 Map, but I'd like to separate these values into individual arrays without having to loop multiple times.

Here is my attempt so far:

    let list = [
        {
            "name": "namee 1",
            "type": "type 1",
            "deal_type": "dealtype1"
        },
        {
            "name": "namee 2",
            "type": "type 2",
            "deal_type": "dealtype2"
        },
        {
            "name": "namee 3",
            "type": "type 3",
            "deal_type": "dealtype3"
        },
        {
            "name": "namee 1",
            "type": "type 1",
            "deal_type": "dealtype1"
        }
    ]

  const summary = test.map(item => ({ deal_type: item.deal_type, type: item.type}));

The desired outcome would be the following output from one .Map loop:

type = ["type 1", "type 2", "type 3"] 
deal_type = ["dealtype1", "dealtype2", "dealtype3"]

CodePudding user response:

You can try either of these: With map function:

const types = list.map((item) => item.type); 
const deal_type = list.map((item) => item.deal_type);

Or with forEach:

const types = [], deal_type = [];  
list.forEach((item) => {   
types.push(item.type);   
deal_type.push(item.deal_type); 
});

CodePudding user response:

Try this one..

const type = list.map((item) => item.type);  
const deal_type = list.map((item) => item.deal_type);
  • Related