Home > Blockchain >  How can I make the search for find short in the object contained within the object?
How can I make the search for find short in the object contained within the object?

Time:12-11

The following function returns the object it finds using the find method on the object inside the object. But I think it's a very long road. Can I write shorter?

Thank you for your help

let customers = [
  {
    active: true,
    id: 1,
    products: {
      householdProducts: [
        {productId: 5, name: "food processor"},
        {productId: 6, name: "mop"},
      ],
      carProducts: [
        {productId: 3, name: "headlight"},
        {productId: 4, name: "wiper"},
      ],
    },
  },
  {
    active: true,
    id: 2,
    products: {
      householdProducts: [
        {productId: 1, name: "cabinet"},
        {productId: 2, name: "lamp"},
      ],
      carProducts: [
        {productId: 7, name: "horn"},
        {productId: 8, name: "handbrake"},
      ],
    },
  },
];

let whichProducts = "householdProducts";

function checkInCustomer(id, name) {
  let result = undefined;

  for (let i = 0; i < customers.length; i  ) {
    result = customers[i]["products"][whichProducts].find((product) => product?.productId === id && product?.name === name);
    if (result !== undefined) {
      break;
    }
  }
  return result;
}

console.log(checkInCustomer(3, "headlight"));

CodePudding user response:

Your outer for loop can be replaced with a call to .find(), and your inner .find() method can become a call to .some(). The .some() method will returns true once it finds a match based on the callback function you supply it with, otherwise, it will return false. In the below .some() function call, I've used destructuring assignment to grab the properties productId and name which are then compared with the function arguments. I've also removed the dependencies your function has on global scope data, and instead passed those through as arguments to allow your function to behave standalone.

See example below:

const customers = [ { active: true, id: 1, products: { householdProducts: [ {productId: 5, name: "food processor"}, {productId: 6, name: "mop"}, ], carProducts: [ {productId: 3, name: "headlight"}, {productId: 4, name: "wiper"}, ], }, }, { active: true, id: 2, products: { householdProducts: [ {productId: 1, name: "cabinet"}, {productId: 2, name: "lamp"}, ], carProducts: [ {productId: 7, name: "horn"}, {productId: 8, name: "handbrake"}, ], }, }, ];

function checkInCustomer(data, sId, sName, whichProducts = "householdProducts") {
  return data.find(customer =>
    customer.products[whichProducts].some(({productId, name}) => productId === sId && name === sName)
  );
}

console.log(checkInCustomer(customers, 6, "mop"));

  • Related