add the array element to the object

How can I extract values from a nested array and push them into a new single object?

const Ll = [
  {
    _id: 'milk',
    category: [
      [
        {
          name: 'Alfred',
          job: 'manager'
        },
        {
          name: 'Mark',
          job: 'manager'
        }
      ]
    ]
  },
  {
    _id: 'grocery',
    category: [
      [
        {
          name: 'William',
          job: 'manager'
        }
      ]
    ]
  }
]

I would like the resulting object to look like this:

const obj = {
  milk: [
    {
      name: 'Alfred',
      job: 'manager'
    },
    {
      name: 'Mark',
      job: 'manager'
    }
  ],
  grocery: [
    {
      name: 'William',
      job: 'manager'
    }
  ]
}

Is there a way to achieve this? Thank you!

Answer №1

If you want to achieve this, consider using the Array.prototype.reduce() method in JavaScript. Iterate through the array and group its elements based on the _id property.

const data = [
  {
    _id: 'milk',
    category: [
      [
        {
          name: 'Alfred',
          job: 'manager',
        },
      ],
    ],
  },
  {
    _id: 'grocery',
    category: [
      [
        {
          name: 'William',
          job: 'manager',
        },
      ],
    ],
  },
  {
    _id: 'milk',
    category: [
      [
        {
          name: 'Mark',
          job: 'manager',
        },
      ],
    ],
  },
];
const result = data.reduce((previous, current) => {
  const prev = previous;
  const key = current._id;
  prev[key] = prev[key] ?? [];
  prev[key].push(...current.category.flat());
  return prev;
}, {});
console.log(result);

Using ES6:

const data = [
  {
    _id: 'milk',
    category: [
      [
        {
          name: 'Alfred',
          job: 'manager',
        },
      ],
    ],
  },
  {
    _id: 'grocery',
    category: [
      [
        {
          name: 'William',
          job: 'manager',
        },
      ],
    ],
  },
  {
    _id: 'milk',
    category: [
      [
        {
          name: 'Mark',
          job: 'manager',
        },
      ],
    ],
  },
];
const result = data.reduce((previous, current) => {
  const prev = previous;
  const key = current._id;
  prev[key] = prev[key] || [];
  prev[key].push(...current.category.reduce((accumulator, value) => accumulator.concat(value), []));
  return prev;
}, {});
console.log(result);

Answer №2

Check out this solution:

let newData = {};
data.forEach(item => {
    const itemList = item.category.reduce((acc, value) => acc.concat(value), []);
    newData[item._id] = newData[item._id] ? [...newData[item._id], ...itemList] : [...itemList];
});

console.log(newData);

Answer №3

To achieve this, consider utilizing the reduce method along with an empty object as the starting point.

This approach involves:

const data = [ { _id: "milk", category: [ [ { name: "Alfred", job: "manager", }, { name: "Mark", job: "manager", }, ], ], }, { _id: "grocery", category: [ [ { name: "William", job: "manager", }, ], ], }, ];

const res = data.reduce(
  (acc, { _id, category }) => ({ ...acc, [_id]: category.flat() }),
  {}
);

console.log(res);

Answer №4

let uniqueKeys = [...new Set(data.map(item => item._id))];

let updatedData = uniqueKeys.reduce((acc, curr) => {
  const value = data.filter(({ _id }) => _id === curr).map(({ category }) => {
    return {
      ...category[0][0]
    }
  });

  return {
    ...acc,
    [curr]: value
  }
}, {});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular is not refreshing the DOM, but it is instead logging the data to the console

Can anyone explain why AngularJS is not updating the div, even though I can see the data in the console? What am I overlooking here? Here is a fiddle I created: function jsonp_example($scope, $http) { $scope.doRequest = function() { var url ...

A step-by-step guide for invoking a JSON-based API

I'm currently facing an issue with calling a JSON-based authentication API. The API requires two parameters, username and password, to be passed in JSON format. What could be the mistake in my approach? Below is the snippet of my current test code: ...

Combining various API requests within a Vue component, which includes a for loop

I'm delving into the world of API chaining, specifically trying to link two different API calls within a 'notes' Vue component. My knowledge of promises is basic at best, but I'm eager to enhance my skills in this area. The initial API ...

Elevate your frontend development game with the powerful combination of Vue js 3

I've been attempting to add this dependency, but I keep receiving an error message stating that it doesn't exist and Vue 3 is unable to resolve the component. Click here to visit the npm page for vue-phone-number-input Any assistance you can pr ...

Sharing Angular 4 components in my project - collaboration at its finest

I have been working on an Angular project that consists of a variety of UI components. I would like to make these components available for use in other Angular projects and share them within the npm community. All of the components are located in a shared ...

Express - Unhandled promise rejection detected

I am working with two tables, one for graduates and another for mentors. My goal is to determine which table an email belongs to by using the provided endpoint. router.post("/reset/:email", async (req, res) => { //searching for the table from ...

When the enter key is pressed, the form will be automatically submitted

My current implementation includes the utilization of Bootstrap input tags as shown below: myPage.html <form th:object="${field}" name="modal" method="post" th:action="@{/ajouterFieldEcran}"> ... <div class="form-group row"> <label ...

The Error Message: "404 Not Found - Your Form Submission Could Not

Greetings, I am currently immersing myself in learning NodeJS and the Express framework. However, I have encountered an issue when attempting to submit a form that is supposed to go to the '/users/register' URL. It appears that my app.js is unabl ...

Is it necessary to make a distinct route for SocketIO implementation?

I am new to Socket.IO and I recently completed the chat tutorial in the documentation along with some additional tasks to gain a better understanding of how it works. Currently, I am attempting to establish a connection between a NodeJS server and a React ...

Error: The function "split" is not a valid function in React hook form and has caused

https://i.sstatic.net/k5wkl.png I'm having trouble with the register function and I followed the documentation. However, it's still showing an error - https://i.sstatic.net/jL6pc.png Any assistance would be greatly appreciated. ...

After making changes to the variables in my forEach loop, they revert back to their initial values

I have been attempting to create a query to retrieve all earnings and withdrawal amounts and then sum them up. However, I have encountered an issue where, after the forEach loop finishes and exits, the updated values stored in a variable revert back to t ...

The error message encountered with React Easy DatePicker is: "Uncaught ReferenceError: process is not defined."

I am attempting to integrate the stylish DatePicker from https://www.npmjs.com/package/sassy-datepicker?activeTab=readme Here is my implementation : import DatePicker from "sassy-datepicker"; function App() { const [date, setDate] = useSta ...

Is there a method to compare a specific value at an index with all subsequent values until a match is found?

Imagine having an array called `$ar`: $ar = array(0,1,0,0,0,1,0) I am interested in comparing the value at $ar[2], which is 0, with all the values to its right until a mismatch occurs. This means checking if $ar[2] == $ar[3], $ar[2] == $ar[4], and so on, ...

How to align borders of adjacent 2D arrays and Blur them (Heightmaps)

I've been struggling with this issue for a while now, searching high and low for a solution but coming up empty-handed. I am working with 2D arrays of floats in C#, which always form a square when put together. These arrays come in sizes of 129x129, 5 ...

Identify and remove numbers from an array that have the same digit, without having prior knowledge of which digit it

Is there an easy way to separate values in an array of random numbers between 0-99 based on their first and second digits? I need two arrays: one for values that share the same first digit, and another for values that share the same second digit. The actua ...

JavaScript code for client-side implementation using Node.js

As I work on developing a web application, I encounter the need to interact with an API that lacks JSONP/CORS support. Initially, my solution was to establish a server with PHP code and utilize ajax calls. However, my discovery of this node module offers ...

What is the best way to manage a JSON feed that does not provide any results?

Excuse my lack of experience as I pose my first question. Using FullCalendar 5.10.1, I am working on retrieving events dynamically associated with Festivals. I have followed the 'events (as a json feed)' pattern from the documentation. When ther ...

Activating CORS for .ajax POST requests

I am encountering an error with my .ajax request that reads as follows: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.com/api/GetData. This issue can be resolved by either moving the resource to ...

Ways to shift duplicates to the beginning of an Object array?

I am working with a variable that contains an array of objects let Obj1 = [ {Id: 123, name: 'A'}, {Id: 124, name: 'B'}, {Id: 125, name: 'C'}, {Id: 126, name: 'D'}, {Id: 127, name: 'E&apo ...

Instructions on how to export an HTML table to Excel or PDF by including specific buttons using PHP or JavaScript

I created a table to display leave details of employees with sorting options from date to date. Now, I need to include buttons for exporting the data to Excel and PDF formats. Check out the code below: <form name="filter" method="POST"> <in ...