score:0

var messages = [];

function getMessage(index) {
    if (a[index - 1].message !== undefined) {
        messages.push(a[index - 1].message);
    }
    if (a[index - 1].render) {
        getMessage(a[index - 1].stageID);
    }
}

getMessage(1);

score:0

const posts = [
  { "algID": 0, "render": true, "message": "first message", "stageID": "3" },
  { "algID": 0, "render": false, "message": "second message", "message_type": "text" },
  { "algID": 0, "render": true, "message": "third message", "message_type": "text", "stageID": "5" },
  { "algID": 0, "render": false },
  { "algID": 0, "render": false, "stageID": "4" },
  { "algID": 0, "render": false }
];

const find_message_chain = post => {
  const index = parseInt( post.stageID ) - 1;
  // If we have render: true, we will need to look for the next post as well.
  // By recursively calling find_chain and concatenating all the results, we get a single, one lvel deep array instead of nested arrays we have to .flat() at the end.
  if ( post.render && post.message ) return [ post.message, ...find_message_chain( posts[ index ]) ];
  // If we do not have render true, but do have a message, this post will br the last one in the chain, so we return it.
  else if ( post.message ) return [ post.message ];
  // If no message exists, we do not want to return the post, since the chain ends.
  else return [];
};

const messages_for_post_0 = find_message_chain( posts[ 0 ] );

console.log( messages_for_post_0 );

const all_messages_per_post = posts.map( find_message_chain );

console.log( all_messages_per_post );

score:2

var data = [{ algID: 0, render: true, message: "first message", stageID: "3" }, { algID: 0, render: false, message: "second message", message_type: "text" }, { algID: 0, render: true, message: "third message", message_type: "text", stageID: "5" }, { algID: 0, render: false }, { algID: 0, render: false, stageID: "4" }, { algID: 0, render: false }],
    result = [],
    i = 0;

while (data[i]) {
    if (data[i].message) result.push(data[i].message);
    if (data[i].render) {
        i = data[i].stageID - 1;
        continue;
    }
    i++;
}

console.log(result);

Related Query

More Query from same tag