0

I have a complex deeply nested JSON in Node.js and I have trouble extracting certain data. I need all the ids that belong only to the items, my problem is that the folders also have an id field so I cannot access only the id from the items. This is an example json:

{
  id: "0",
  name: null,
  parentId: null,
  folderType: "chatCannedMessages",
  folders: [
    {
      id: 3195588631115178,
      name: "Testfolder",
      parentId: null,
      folderType: "chatCannedMessages",
      folders: [
        {
          id: "3195588620182363",
          name: "Subfolder",
          parentId: "3195588631115178",
          folderType: "chatCannedMessages",
          folders: [
            {
              id: "3206824598737435",
              name: "Interesting",
              parentId: "3195588620182363",
              folderType: "chatCannedMessages",
              folders: [],
              items: [
                {
                  id: "3208409930553392",
                  name: "Canned Message",
                  folderId: "3206824598737435",
                  updated: "2022-05-27T07:28:40.450Z",
                  frontendFolderId: null,
                  text: "<p>This is an HTML with Image.</p>",
                  keywords: "test",
                  subject: "What kind of subject",
                  slashCommand: "test",
                  language: "en-US",
                  setupItemId: "3208409930553392",
                },
              ],
            },
          ],
          items: [
            {
              id: "3195595211854821",
              name: "Message in subfolder",
              folderId: "3195588620182363",
              updated: "2022-05-19T12:05:39.503Z",
              frontendFolderId: null,
              text: "Message in subfolder",
              keywords: "test",
              subject: "Message in subfolder",
              slashCommand: "sub",
              language: "bn-BD",
              setupItemId: "3195595211854821",
            },
          ],
        },
      ],
      items: [],
    },
  ],
  items: [
    {
      id: "2888102250465731",
      name: "bye",
      folderId: null,
      updated: "2022-05-25T11:15:36.367Z",
      frontendFolderId: null,
      text: "Thanks for contacting us.  Please do not hesitate to contact us again if we can be of further assistance.",
      keywords: "bye",
      subject: null,
      slashCommand: null,
      language: null,
      setupItemId: "2888102250465731",
    },
  ],
};

The output that I want to achieve here is an array, looking like this:

["3208409930553392", "3195595211854821", null]
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
sufocator
  • 39
  • 3
  • Is the requirement to fetch the values for all `id` properties of objects in all `items` arrays? Why is `"2888102250465731"` not included in the desired result? Where does the `null` come from? – outis Oct 10 '22 at 22:12
  • Does this answer your question? [How can I access and process nested objects, arrays, or JSON?](/q/11922383/90527) – outis Oct 11 '22 at 00:21

3 Answers3

0

Iterate it is not that complex json. Just items and folders.

var obj={id:"0",name:null,parentId:null,folderType:"chatCannedMessages",folders:[{id:0xb5a5ef534b5aa,name:"Testfolder",parentId:null,folderType:"chatCannedMessages",folders:[{id:"3195588620182363",name:"Subfolder",parentId:"3195588631115178",folderType:"chatCannedMessages",folders:[{id:"3206824598737435",name:"Interesting",parentId:"3195588620182363",folderType:"chatCannedMessages",folders:[],items:[{id:"3208409930553392",name:"Canned Message",folderId:"3206824598737435",updated:"2022-05-27T07:28:40.450Z",frontendFolderId:null,text:"<p>This is an HTML with Image.</p>",keywords:"test",subject:"What kind of subject",slashCommand:"test",language:"en-US",setupItemId:"3208409930553392"},]},],items:[{id:"3195595211854821",name:"Message in subfolder",folderId:"3195588620182363",updated:"2022-05-19T12:05:39.503Z",frontendFolderId:null,text:"Message in subfolder",keywords:"test",subject:"Message in subfolder",slashCommand:"sub",language:"bn-BD",setupItemId:"3195595211854821"},]},],items:[]},],items:[{id:"2888102250465731",name:"bye",folderId:null,updated:"2022-05-25T11:15:36.367Z",frontendFolderId:null,text:"Thanks for contacting us.  Please do not hesitate to contact us again if we can be of further assistance.",keywords:"bye",subject:null,slashCommand:null,language:null,setupItemId:"2888102250465731"},]};

result = [];

function iterate(obj) {
  (obj.items || []).forEach(function(item) {
    result.push(item.id)
  });
  (obj.folders || []).forEach(function(item) {
    iterate(item)
  });
}
iterate(obj);
console.log(result)
IT goldman
  • 14,885
  • 2
  • 14
  • 28
0

const data = {
  id: "0",
  name: null,
  parentId: null,
  folderType: "chatCannedMessages",
  folders: [{
    id: 3195588631115178,
    name: "Testfolder",
    parentId: null,
    folderType: "chatCannedMessages",
    folders: [{
      id: "3195588620182363",
      name: "Subfolder",
      parentId: "3195588631115178",
      folderType: "chatCannedMessages",
      folders: [{
        id: "3206824598737435",
        name: "Interesting",
        parentId: "3195588620182363",
        folderType: "chatCannedMessages",
        folders: [],
        items: [{
          id: "3208409930553392",
          name: "Canned Message",
          folderId: "3206824598737435",
          updated: "2022-05-27T07:28:40.450Z",
          frontendFolderId: null,
          text: "<p>This is an HTML with Image.</p>",
          keywords: "test",
          subject: "What kind of subject",
          slashCommand: "test",
          language: "en-US",
          setupItemId: "3208409930553392",
        }, ],
      }, ],
      items: [{
        id: "3195595211854821",
        name: "Message in subfolder",
        folderId: "3195588620182363",
        updated: "2022-05-19T12:05:39.503Z",
        frontendFolderId: null,
        text: "Message in subfolder",
        keywords: "test",
        subject: "Message in subfolder",
        slashCommand: "sub",
        language: "bn-BD",
        setupItemId: "3195595211854821",
      }, ],
    }, ],
    items: [],
  }, ],
  items: [{
    id: "2888102250465731",
    name: "bye",
    folderId: null,
    updated: "2022-05-25T11:15:36.367Z",
    frontendFolderId: null,
    text: "Thanks for contacting us.  Please do not hesitate to contact us again if we can be of further assistance.",
    keywords: "bye",
    subject: null,
    slashCommand: null,
    language: null,
    setupItemId: "2888102250465731",
  }, ],
};

const ids = []

function traverse(obj, parent) {
  if (obj === null) return
  if (Array.isArray(obj)) {
    for (const item of obj) {
      traverse(item, parent)
    }
  } else if (typeof obj === 'object') {
    if (parent === 'items') {
      ids.push(obj.id)
    } else {
      for (const [key, value] of Object.entries(obj)) {
        traverse(value, key)
      }
    }
  }
}

traverse(data, '')

console.log(ids)
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    While this code may be useful to the OP, providing [additional context](//meta.stackoverflow.com/q/392712/90527) regarding why & how it works, and when it should be used will improve its long-term value by helping other readers. – outis Oct 11 '22 at 00:06
0

You can solve your problem by applying a recursive logic. The pattern is that if the last descendant object was items, then any direct object descendants (with possible arrays in-between of the hierarchy) are having ids that we need to collect

let input = {
    items: [
        {
            id: 1,
            foo: [
                {
                    id: 2,
                    items: [
                        {
                            id: 3,
                            items: [
                                {
                                    bar: [
                                        {
                                            id: 4
                                        }
                                    ]
                                },
                                {
                                    id: 5
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

let ids = [];
function getItemIDs(obj, wasItems = false) {
    if (Array.isArray(obj) || (typeof obj === "object")) {
        if (wasItems && (!Array.isArray(obj))) {
            ids.push(obj.id);
        }
        for (let key in obj) {
            if (Array.isArray(obj[key]) || (typeof obj[key] === "object")) {
                getItemIDs(obj[key], (key === "items") || (wasItems && !Array.isArray(obj[key])))
            }
        }
    }
}
getItemIDs(input);
console.log(ids);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175