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

I'm having trouble with installing nx as it keeps showing the error message 'Platform Dependency for NX is Missing.'

I encountered an issue when running npm install: $ npm i npm WARN deprecated @babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b5b475e4c4245065b59445b44584a470648474a5858065b59445b4e595f424e586b1c051a13051d">[email  ...

Unable to make getJSON function properly with CodeIgniter

I'm experimenting with using getJSON to retrieve the most recent data from my database. So far, I've stored it in an array and used json_encode(the array). This method successfully displays the information on the view, but the problem lies in the ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

removing a property from an object using AngularJS

Currently, I am working on a project involving AngularJS. The main goal of this project is to create a dynamic JSON generator using AngularJS. I have already developed the initial version and it works well. However, there is a minor issue with my applicati ...

What is the best way to show a tooltip alongside highlighted text?

How can I display a tooltip (using qTip) next to selected text? The code below captures the selected text in the console, but the tooltip is not displayed. <div class='test'>Actual text will be much longer...Test Test Test Test Test Test T ...

When the jQuery document is ready, it typically returns null, but the console can still access and display

I have encountered an issue while working on a solution within a CMS (EPiServer). When I utilize console.log to check my object, it displays a null value. $(document).ready(function () { console.log("$('.EPiRequester').html() =" + $('. ...

Passing an array of ID's between two components in Angular: A comprehensive guide

Greetings fellow readers, I have encountered a new challenge in my Angular project. I need to pass an array of IDs from one component to a completely unrelated component. Most solutions suggest using ViewChild, Input, or Output, but since the components ar ...

Arranging data using jqGrid's Inline Editing Feature

Can the data on jqGrid be sorted directly on the client side while using inline editing? It appears that the data is not being sorted when the row is editable, even if the row header is clicked. ...

Populate an ASP Form using Javascript in Android Studio

Being relatively new to Android studio, I have been experimenting with various methods but now need some assistance. I am looking to input data into an ASP.NET Website-form using Android studio. The traditional JavaScript approach does not seem to be effec ...

Receiving a null value in Action after an AJAX call in Struts 2

I have been working on sending AJAX requests to an Action in which I send a parameter from a JSP page. The issue I am facing is that my Action class receives the Ajax request, but the params being sent with the AJAX call are showing as null in the Action c ...

Jquery Visualization Chart not displaying

I am struggling to get the jquery visualization to work properly. Although the table and caption appear fine, there is no data showing up in the chart. I've carefully followed the example and searched for any issues, but I can't identify what&apo ...

What is the best way to send multiple variables to a url using jQuery ajax?

I am having trouble passing multiple values in the method below. Can someone help me with the correct syntax? I have attempted data: ('keyword='+$(this).val(),'id='10), as well as data: {'keyword='+$(this).val(),'id=&a ...

Looking for guidance on how to specify the angular direction in the ng-repeat

I am facing a challenge with the structure of my ng-repeat directive and I am having trouble navigating through it. Here is a representation of the data in array format JSON style {"data":[ ["sameer","1001", [ {"button_icon": ...

Error: Issue with parsing integer in JavaScript

I'm in the process of developing a dice game that involves rolling two dice and determining the sum. The goal is to display the running total next to the dice. However, I'm encountering an issue where NaN (Not a Number) is being displayed. Here i ...

configure dynamic content within the slider element

Currently, I am experimenting with two jQuery plugins (awkward/Coda Slider 3) to implement a sliding effect for DIV content. Everything seems to be working smoothly until I attempt to set dynamic content (using JavaScript) after creating the plugin object. ...

Error: JavaScript encountered an unterminated string literal issue

Whenever I try to add the following two lines in the section of my application's homepage, my browser throws a JavaScript error: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window. ...

Not all words are compatible with word-wrap, don't you think?!

I have a situation where I used the following CSS properties for a div: word-wrap: break-word; text-align: justify; When a single word is too long to fit within the width of the div, it wraps or breaks into multiple lines. However, if a second word with ...

Chess.js TypeScript declaration file for easy implementation

Currently, I am delving into learning typescript and have taken up the challenge of crafting a declaration file for the chess.js library. However, it seems that I am struggling to grasp the concept of creating one. Whenever I attempt to import the library ...

Including a Pinterest image hover widget following the completion of an Ajax load

I have implemented the Pinterest image hover widget on my website to allow users to easily pin images to their Pinterest accounts. You can find the widget here. (Make sure to click the image hover radio button under button type to see the one I am using.) ...

The method for storing a user's choice in my array and subsequently selecting an element at random

Seeking assistance in developing a program that can play an audio list at various durations. The plan is to have the duration for elements 4 through 8 based on user selection, with the program playing each element within that range during the initial round ...