简体   繁体   中英

Sorting out array of parent child relations where two children share a parent from an array and display it using div

I have the following data which gets served from a neo4j query, The data that gets sent back is in the format

home->parent->child1
home->parent->child2

home->parent2->child1

home->parent3->child1
home->parent3->child2
home->parent3->child3

I am trying to use javascript to display html which should be like this

<div id="parent1">
  <div id="child1"></div>
  <div id="child2"></div>
</div>
<div id="parent2">
  <div id="child1"></div>
</div>

i tried loopong throigh the query and trying to get the parent to be the index of an object and the child to be values under it

i would do this like this in php

$jsonContents = (object)("parent"=>"child","parent"=>"child"....);
$array = array();
foreach($jsonContents as $jsCo=>$jsoCont){
  $array[$jsoCont->parent][] = $jsoCont->child;
}

this would return the

$array as

home->parent1->[0]->child
             ->[1]->child
      parent2->[0]->child...

This would let me avoid the check for uniqueness of the home parent category as well as put them in a hierarchy so i can interpret it properly in my View part of MVC, to create my div structure.

this is the url for the example json data

http://www.jsoneditoronline.org/?id=bdda268982eb431d361c25e9035bbc99

No answers to this, solved it by myself. Here

var data = 'data shown in link above';
var myArr = [];

$.each(data, function(index, element) {
  var parent = String(element.parent.properties.name);
  var child = String(element.child.properties.name);

  if(myArr[parent]){
    myArr[parent][(myArr[parent].length)] = child;
  } else {
    myArr[parent] = Array(child);
  }

});

Hope this helps people. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM