Jack
Jack

Reputation: 1999

Get parent array from child array

In the code below I can easily enter into a subarray within the array with current = current[0].

var root = [
  [
    'Value 1',
  ]
];
var current = root;

current = current[0];

current.push('Value 2');

document.write(JSON.stringify(root));

How can I do the reverse and go up a level? In this example, current would become:

[['Value 1', 'Value 2']]

The only way I can think of doing this would be looping, but duplicates would be very probably and problematic. All I've found online is looping, which won't work as a mention in the last sentence.

EDIT

I'm looping through a large string and converting it to a tree. Certain characters will require a indent in the tree or a separate branch, while others will require an outdent and return to the parent function. I've achieved the indents by having a current variable just enter a new subarray as suggested here. I just need a way to exit with a different character.

Upvotes: 0

Views: 977

Answers (2)

imvain2
imvain2

Reputation: 15847

Simply pushing BEFORE setting current variable will work.

var root = [
  [
    'Value 1',
  ]
];
var current = root;

root.push("AAA");

current = current[0];

current.push('Value 2');

document.write(JSON.stringify(root));

Upvotes: 0

Klaycon
Klaycon

Reputation: 11080

You can't.

Arrays have no concept of a "parent" or anything. They don't care where their references are being held. However, if you really really need to, you can implement the concept of a "parent" yourself using a simple recursive function setting properties of the arrays - see below:

var root = [
  [
    'Value 1',
  ]
];

function setParents(root) {
  for(var i = 0; i < root.length; i++) {
    if(Array.isArray(root[i])) {
      root[i].parent = root;
      setParents(root[i]);
    }
  }
}

setParents(root);

var current = root;
current = current[0];
current.push('Value 2');
document.write(JSON.stringify(root));

current = current.parent;
console.log(current);

This makes use of the fact that array properties don't show up when logged or serialized as JSON, only their elements. So they're kind of "hidden" in a sense. It's a bit hacky but could work for you.

However, I recommend you simply avoid overwriting current - there's not really a great need to use it like a cursor traversing some hierarchy structure.

Upvotes: 1

Related Questions