简体   繁体   中英

how to convert array into new array of parent children

I have restaurant data array, I should make another array by grouping items by category that belongs to, I should convert this array:

[
     {
      "category":  {
        "title": "Appetizers",
      },
      "id": 1,
      "price": "10",
      "title": "Spinach Artichoke Dip",
    },
     {
      "category":  {
        "title": "Appetizers",
      },
      "id": 2,
      "price": "10",
      "title": "Hummus",
    },

     {
      "category":  {
        "title": "Salads",
      },
      "id": 3,
      "price": "7",
      "title": "Greek",
    },
    {
      "category":  {
        "title": "Salads",
      },
      "id": 4,
      "price": "9",
      "title": "Beyn",
    }
  ]

into a new array that should be as final result like this:

  [{
    "category": "Appetizers",
    "items" : ["Spinach Artichoke Dip","Hummus"]
  },
  {
    "category" : "Salads",
    "items" :["Greek", "Beyn"]
  }
]

I can't find how to do it could you please help

Lets say that your data is a constant called data

So you can do this:

const data = [
   {
    "category":  {
      "title": "Appetizers",
    },
    "id": 1,
    "price": "10",
    "title": "Spinach Artichoke Dip",
  },
   {
    "category":  {
      "title": "Appetizers",
    },
    "id": 2,
    "price": "10",
    "title": "Hummus",
  },

   {
    "category":  {
      "title": "Salads",
    },
    "id": 3,
    "price": "7",
    "title": "Greek",
  },
  {
    "category":  {
      "title": "Salads",
    },
    "id": 4,
    "price": "9",
    "title": "Beyn",
  }
];

const result = [];

data.forEach((item) => {
  const category = item.category.title;
  const title = item.title;

  let foundCategory = result.find((c) => c.category === category);
  if (foundCategory) {
    foundCategory.items.push(title);
  } else {
    result.push({ category, items: [title] });
  }
});

console.log(result);

Now your desired result will be stored in result

happy coding

const itemsToCategories = (itemsArr) => {
  const store = {};

  itemsArr.forEach(item => {
    const categoryTitle = item.category.title;
    if (!store[categoryTitle]) store[categoryTitle] = [];
    store[categoryTitle].push(item.title);
  });

  return Object.entries(store).map(([category, items]) => ({ category, items}));
};

This solution should be a bit faster than the accepted answer for large data sets. The main difference is the use of an object ( store ) instead of an array, so lookups by the category title are more efficient. Then we build an array from that object at the end.

This does have more overhead than the accepted solution above, so for smaller data sets, this ends up being slower in comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM