Home > Back-end >  how to combine the objective arrays have the save same key in javascript
how to combine the objective arrays have the save same key in javascript

Time:01-30

var saperatedIngredients =  [{
    ingredients: (2) ['Aar maach', 'Fish fillet']
    searchfilter: "marine fish"
    },
    {ingredients: ['Active dry yeast']
    searchfilter: "yeast"
    },
    {ingredients: (5) ['Ajwain', 'Cumin powder', 'Tamarind', 'Tamarind paste', 'Tamarind water']
    searchfilter: "miscellaneous derived edible product of plant origin"
    }
   ]

but i want the output like this

const IngredientsArray = ['Aar maach', 'Fish fillet', 'Active dry yeast','Ajwain', 'Cumin powder', 'Tamarind', 'Tamarind paste', 'Tamarind water']

anyone help me out for this problem

CodePudding user response:

You can simply use flatMap()

var saperatedIngredients =  [{
    ingredients:  ['Aar maach', 'Fish fillet'],
    searchfilter: "marine fish"
    },
    {ingredients: ['Active dry yeast'],
    searchfilter: "yeast"
    },
    {ingredients:  ['Ajwain', 'Cumin powder', 'Tamarind', 'Tamarind paste', 'Tamarind water'],
    searchfilter: "miscellaneous derived edible product of plant origin"
    }
   ]
 
const res = saperatedIngredients.flatMap(x => x.ingredients);

console.log(res)

CodePudding user response:

You could also use reduce:

const ingredients = saperatedIngredients.reduce( (acc, item) => {
 acc.push(...item.ingredients)
 return acc
}, [])
  •  Tags:  
  • Related