Home > Software engineering >  How to filter object array and return only 2 of 4 properties and formated?
How to filter object array and return only 2 of 4 properties and formated?

Time:03-11

I receive from API the following object array:

{id: 0, color: 'Red', code:'AAA'}
{id: 1, color: 'Blue', code:'BBB'}
{id: 2, color: 'Orange', code:'CCC'}
{id: 3, color: 'Black', code:'DDD'}

how can I return it for another array but only if id is > 1 and like this:

const arrayFiltered = { 'Orange#CCC', 'Black#DDD' }

I need convert it in a string array and concatenate 2 atributes...

CodePudding user response:

Assuming given array is givenArr

const givenArr = [
  {id: 0, color: 'Red', code:'AAA'},
  {id: 1, color: 'Blue', code:'BBB'},
  {id: 2, color: 'Orange', code:'CCC'},
  {id: 3, color: 'Black', code:'DDD'}
]

result = givenArr.filter((val) => val.id > 1).map((item) => `${item.color}#${item.code}`)

console.log(result)

CodePudding user response:

Your desired output is invalid. arrayFiltered will be an array not an object, its output would be like ['Orange#CCC', 'Black#DDD']

const arrayFiltered = arrayInput.filter(c => c.id > 1).map(c => c.color c.code);

  • Related