Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this:

{
  "comments": [
    {
      "id": 1,
      "content": "lorem ipsum",
      "answers": []
    },
    {
      "id": 2,
      "content": "lorem ipsum",
      "answers": [
        {
          "id": 30,
          "content": "lorem ipsum"
        }
      ]
    },
    {
      "id": 3,
      "content": "lorem ipsum",
      "answers": [
        {
          "id": 99,
          "content": "lorem ipsum"
        },
        {
          "id": 103,
          "content": "lorem ipsum"
        }
      ]
    },
    {
      "id": 5,
      "content": "comment",
      "answers": []
    }
  ]
}

My goal is to create an array that includes the id of all comments, regardless of whether they are main comments or answers.

The final array should look like this:

[1, 2, 3, 5, 30, 99, 103]

Is it possible to achieve this using only map, reduce, and filter?

What other approaches could I consider?

Answer №1

If you prefer using the flat method:

const data = {comments:[{id:1,content:"lorem ipsum",answers:[]},{id:2,content:"lorem ipsum",answers:[{id:30,content:"lorem ipsum"}]},{id:3,content:"lorem ipsum",answers:[{id:99,content:"lorem ipsum"},{id:103,content:"lorem ipsum"}]},{id:5,content:"comment",answers:[]}]};

function findIds(obj) {
  return obj.comments.map(com => {
    return [ com.id, ...com.answers.map(ans => ans.id) ]
  })
  .flat()
  .sort((a, b) => a - b);
}

console.log( findIds(data) ); // [1,2,3,5,30,99,103]

Alternatively, if you prefer to use only map and reduce:

const data = {comments:[{id:1,content:"lorem ipsum",answers:[]},{id:2,content:"lorem ipsum",answers:[{id:30,content:"lorem ipsum"}]},{id:3,content:"lorem ipsum",answers:[{id:99,content:"lorem ipsum"},{id:103,content:"lorem ipsum"}]},{id:5,content:"comment",answers:[]}]};

function findIds(obj) {
  return obj.comments.reduce((res, com) => {
    return [ ...res, com.id, ...com.answers.map(ans => ans.id) ]
  }, [])
  .sort((a, b) => a - b);
}

console.log( findIds(data) ); // [1,2,3,5,30,99,103]

Answer №2

If you want to achieve the desired result, you can utilize Spread_syntax, concat, reduce, map, and sort methods found in arrays.

Take a look at the code snippet below:

ES6

var obj = {"comments":[{"id":1,"content":"lorem ipsum","answers":[]},{"id":2,"content":"lorem ipsum","answers":[{"id":30,"content":"lorem ipsum"}]},{"id":3,"content":"lorem ipsum","answers":[{"id":99,"content":"lorem ipsum"},{"id":103,"content":"lorem ipsum"}]},{"id":5,"content":"comment","answers":[]}};

let result = obj.comments.reduce((r,o)=>[...r, o.id,...o.answers.map(v=>v.id)],[]);

console.log(result.sort((a,b)=> a-b));

ES5

var data = {"comments":[{"id":1,"content":"lorem ipsum","answers":[]},{"id":2,"content":"lorem ipsum","answers":[{"id":30,"content":"lorem ipsum"}]},{"id":3,"content":"lorem ipsum","answers":[{"id":99,"content":"lorem ipsum"},{"id":103,"content":"lorem ipsum"}]},{"id":5,"content":"comment","answers":[]}};

//This function will return all the ids from the passed array based on the object data above.
function getIDs(obj) {
  var result = obj.comments.reduce(function(res, item) {
    var answers = item.answers.map(function(ans) {
      return ans.id;
    });
    res.push(item.id);//Adding id in array from main list
    return res.concat(answers);//Using contact method for add both arrays values 
  }, []);

  return result.sort(function(a, b) {
    return a - b;
  });
}


console.log(getIDs(data));

Answer №3

Give this code a shot

Your JSON data: myData = { ... }

let output = []
let objects = []
for (let x = 0; x < myData.comments.length; x++){
    let objId = myData.comments[x].id
    output.push(objId)
    objects.push(myData.comments[x].answers)
}
for(let y = 0; y < objects.length; y ++){
    let answersList = objects[y]
    for(let z = 0; z < answersList.length; z++){
        let answer = answersList[z]
        if(answer)             
            output.push(answer.id)
    }
}
console.log(output)

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

Refresh meta tags in a Next.js/React app

In the process of optimizing a website for SEO, I am facing the challenge of updating the meta description's content dynamically without using any third-party libraries. While I have successfully implemented the functionality, it currently requires a ...

Error message shows explicit Typescript type instead of using generic type name

I am looking to use a more explicit name such as userId instead of the type number in my error message for error types. export const primaryKey: PrimaryKey = `CONSUMPTION#123a4`; // The error 'Type ""CONSUMPTION#123a4"" is not assignable to ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

How can I ensure the Jquery datepicker functions correctly?

I've been attempting to create a jsp page with some Jquery functionalities. Unfortunately, despite my best efforts, I am unable to make it work. I have downloaded jquery1.7.1 and jquery-ui1.8.17 (non-mini), renamed them to jquery171.js and jquery-ui. ...

Casting user-defined data types to JSON objects can be achieved using the `jason.simple` library

I'm facing an issue with type casting a user-defined data type, USERS, into a JSON Object. When I tried using .toString() to convert Users into a String, the output was unexpected and incorrect. I then considered converting it into a JSON Object and r ...

Updating a class within an AngularJS directive: A step-by-step guide

Is there a way to change the class (inside directive) upon clicking the directive element? The current code I have updates scope.myattr in the console but not reflected in the template or view: <test order="A">Test</test> .directive("test", ...

Trigger a JavaScript alert message upon clicking the close button

I have encountered an issue with my current code. When I click on the close (X) button, it should display an error message stored in variable s. Previously, the script was functioning correctly but now it is not showing any alerts when I click on the close ...

What is the best way to inject services into non-service class instances in Angular 2?

Here is my current approach, but I'm curious about the recommended practice for working with Angular2? ... class MultitonObject { _http: Http; constructor (appInjector: Injector) { this._http = appInjector.get(Http); } } var ap ...

Enhance your Fastify routes by incorporating Swagger documentation along with specific tags and descriptions

Currently, I am utilizing fastify 3.28.0 in conjunction with the fastify-swagger plugin and typescript 4.6.2. My goal is to include tags, descriptions, and summaries for each route. As per the documentation found here, it should be possible to add descrip ...

Deserializing Jackson JSON-RPC to a universal Object

Deserializing a JSON-RPC object with Jackson has been a challenge for me. The structure of the JSON-RPC is as follows: { "result": "something", "error": null, "id": 1} Specifically, my issue lies in the result property being a generic Object. To tackle ...

Issue with refreshing a material

When updating a transaction, I am encountering the issue of inadvertently deleting other transactions. My goal is to update only one transaction. Can someone review my backend logic to identify the root cause? Schema Details: const mongoose = require(&apo ...

Setting up an SSL certificate for an Express application: A step-by-step guide

I am currently trying to set up my Express server in order to pass the SSL certificate and transition from http to https. After going through the Express documentation, I still haven't been able to find a suitable solution. While some suggestions lik ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...

The option value in mat-autocomplete is not displaying correctly on IOS devices

When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...

Using Python to parse a JSON file containing objects and generate separate JSON files for each object

There is a JSON file in my possession that contains multiple objects structured like this: { "0": { "name": "DIGI#0", "description": "DIGI", "image": "//asset/0", "att ...

Error message encountered: ReferenceError - The subcommand specified in Discord.js Slash Command function is undefined

I have been experimenting with subcommands in a slash command for a discord bot. I plan to have several similar subcommands, so I wanted to create a function that can be called within .addSubCommand, but it seems like it's not functioning correctly. ...

How can I implement a feature in Angular where clicking the edit button loads a form (in a separate component) pre-populated with previous data, along with an update button for

Within the employee-list component, there is a table displaying a list of employees. This table includes an option to edit details. <button type="button" class="btn btn-primary" routerLink="../create-employee">Edit</b ...

An issue occurred when clicking on a line due to the filter

Issue at Hand: Currently, I am facing a problem where selecting an item from the list by clicking on the button leads me to access the information of a different item when the filter is applied. Desired Outcome: I wish to be able to access the correct inf ...