Derek Hough
Derek Hough

Reputation: 45

How to extract value from an object and also an array to form another array?

How do I extract "category" from data and use it as the key for the new output array that includes "name" field from listData array

 const data = {
    "32": {
        "id": 32,
        "category": "Grocery Items",
    }, I 
     "33": {
        "id": 33,
        "category": "Household Items",
    }, 
}

This is the listData array and I would need to extract the data from list.

const listData = [
{
    "data": {
        "list": [
            {
                "id": 1,
                "category_id": 32,
                "title": "Eggs",
                "category": "Grocery Items"
            },
            {
                "id": 2,
                "category_id": 32,
                "title": "Bacon",
                "category": "Grocery Items"
            }
         ]
     }
}
]

Sample Output:

It contains the category from data as the key and data from list array.

const output = {
    "Grocery Items": [
      {
            "id": 1,
            "category": "Grocery Items",
            "name": "Eggs",
      },
      {
            "id": 2,
            "category": "Grocery Items",
            "name": "Bacon",
      },
      ]
}

I tried this but did not give the correct structure

    const output = Object.values(data).map((acc, { title, id }) => {
                let filteredList = [];
                listData.forEach((element) => {
                    console.log(element.data.list)
                    filteredList = element.data.list
                        .filter((item) => item.title === title)
                });

                if (filteredList.length) {
                    acc[title] = filteredList;
                }

                return acc;
            }, {});

Upvotes: 0

Views: 37

Answers (1)

StepUp
StepUp

Reputation: 38104

It is possible to use reduce method. Ad mdn says:

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

So code would look like this:

let obj = array.reduce((acc, cur)  => {
  acc[cur.category_id] = {id: cur.category_id, category: cur.category };
  return acc;
}, {});

An example can be seen here:

const array = [
  {
      "id": 1,
      "category_id": 32,
      "title": "Eggs",
      "category": "Grocery Items"
  },
  {
      "id": 2,
      "category_id": 33,
      "title": "Bacon",
      "category": "Grocery Items 33"
  }
]


let obj = array.reduce((acc, cur)  => {
  acc[cur.category_id] = {id: cur.category_id, category: cur.category };
  return acc;
}, {});

console.log(obj)

Upvotes: 1

Related Questions