get name of object in array when option.amount equals zero

Viewed 103

I'm trying to get an array of names of objects that have options.amount all equals to zero. Thanks for your time. This is what i tryed:

let variants = [        
        {
            name: 'extra',
            options: [
                {
                    name: 'meat',
                    price: 3,
                    amount: 0
                },
                {
                    name: 'cheese',
                    price: 1,
                    amount: 0
                }
            ]
        },
        {
            name: 'sauce',
            options: [
                {
                    name: 'ketchup',
                    price: 2,
                    amount: 1
                },
                {
                    name: 'mayo',
                    price: 1,
                    amount: 0
                }
            ]
        }
    ];

//Expected output = ['extra']

let arrayOfOptionsNames = variants.map(x => x.options.filter(y => y.amount === 0 ? x.name : 0))
console.log(arrayOfOptionsNames)

2 Answers

You could use Array.prototype.filter() and Array.prototype.every() method to get your result. Every method test if every elements of the array pass the test by the given callback function and returns a boolean value.

const variants = [
  {
    name: 'extra',
    options: [
      {
        name: 'meat',
        price: 3,
        amount: 0,
      },
      {
        name: 'cheese',
        price: 1,
        amount: 0,
      },
    ],
  },
  {
    name: 'sauce',
    options: [
      {
        name: 'ketchup',
        price: 2,
        amount: 1,
      },
      {
        name: 'mayo',
        price: 1,
        amount: 0,
      },
    ],
  },
];
const ret = variants
  .filter((x) => x.options.every((y) => y.amount === 0))
  .map((x) => x.name);
console.log(ret);

You could filter and get the wanted property.

let variants = [{ name: 'extra', options: [{ name: 'meat', price: 3, amount: 0 }, { name: 'cheese', price: 1, amount: 0 }] }, { name: 'sauce', options: [{ name: 'ketchup', price: 2, amount: 1 }, { name: 'mayo', price: 1, amount: 0 }] }],
    result = variants
        .filter(({ options }) => options.every(({ amount }) => !amount))
        .map(({ name }) => name);

console.log(result);

Related