Home > Back-end >  Get an array of strings from an array of objects with conditions
Get an array of strings from an array of objects with conditions

Time:03-06

What is the best way to get an array of strings from an array of objects, where you can specify to only take value x where value y=z?

Current solution:

    array = [{
        "Item": "A",
        "Quantity": 2
      },
      {
        "Item": "B",
        "Quantity": 7
      },
      {
        "Item": "C",
        "Quantity": 7
      },
      {
        "Item": "D",
        "Quantity": 7
      },
      {
        "Item": "E",
        "Quantity": 7
      },
      {
        "Item": "F",
        "Quantity": 1
      }
    ];
    
    let filteredValues = array.map((el) => el.Quantity === 7 && el.Item);
    
    console.log(filteredValues)

Expected outcome:

["B", "C", "D", "E"]

Actual outcome:

[false, "B", "C", "D", "E", false]

Additional info: using next.js / react

CodePudding user response:

First, do filter and then do a map to get only the property you need.

const array = [
  { Item: "A", Quantity: 2 },
  { Item: "B", Quantity: 7 },
  { Item: "C", Quantity: 7 },
  { Item: "D", Quantity: 7 },
  { Item: "E", Quantity: 7 },
  { Item: "F", Quantity: 1 },
];

let filteredValues = array
  .filter((el) => el.Quantity === 7 && el.Item)
  .map(({ Item }) => Item);

console.log(filteredValues);

Or, you can use reduce as below.

const array = [
  { Item: "A", Quantity: 2 },
  { Item: "B", Quantity: 7 },
  { Item: "C", Quantity: 7 },
  { Item: "D", Quantity: 7 },
  { Item: "E", Quantity: 7 },
  { Item: "F", Quantity: 1 },
];

let filteredValues = array.reduce((results, el) => {
  if (el.Quantity === 7 && el.Item) {
    results.push(el.Item);
  }
  return results;
}, []);

console.log(filteredValues);

CodePudding user response:

The best way is to use Array.prototype.reduce

let data = [{
    "Item": "A",
    "Quantity": 2
  },
  {
    "Item": "B",
    "Quantity": 7
  },
  {
    "Item": "C",
    "Quantity": 7
  },
  {
    "Item": "D",
    "Quantity": 7
  },
  {
    "Item": "E",
    "Quantity": 7
  },
  {
    "Item": "F",
    "Quantity": 1
  }
];

const result = data.reduce((accumulator, current) => {
  return current["Quantity"] === 7 ? accumulator.concat(current["Item"]): accumulator;
}, [])

console.log(result);

  • Related