JavaScript restructure json based on parent

I am studying the use of reduce in javascript, and I am trying to restructure an Array of Objects in a generic way - need to be dynamic.

flowchart - i get totaly lost

I started with this through.

Every ID becomes a Key. Every PARENT identifies which Key it belongs to.

i have this:

const in = [
  {
    "id": "Ball",
    "parent": "Futebol"
  },
  {
    "id": "Nike",
    "parent": "Ball"
  },
  {
    "id": "Volley",
    "parent": null
  }
]

i want this

out = {
    "Futebol": {
        "Ball": {
            "Nike": {}
        }
    },
    "Volley": {}
}

i try it - and i had miserably failed.

const tree = require('./mock10.json')

// Every ID becomes a Key.
// Every PARENT identifies which Key it belongs to.
const parsedTree = {}
tree.reduce((acc, item) => {
    if (parsedTree.hasOwnProperty(item.parent)){
        if (parsedTree[`${item.parent}`].length > 0) {
            parsedTree[`${item.parent}`][`${item.id}`] = {}
        } else {
            parsedTree[`${item.parent}`] = { [`${item.id}`]: {} }
        }
    } else {
        // i get lost in logic
    }
}, parsedTree)

console.log(parsedTree)

Answer:1

Got a working code for you, feel free to ask me about the implementation

Hope it helps :)

const arrSample = [
  {
    "id": "Ball",
    "parent": "Futebol"
  },
  {
    "id": "Nike",
    "parent": "Ball"
  },
  {
    "id": "Volley",
    "parent": null
  }
]

const buildTree = (arr) => {
  return arr.reduce(([tree, treeMap], { id, parent }) => {
    const val = {}
    treeMap.set(id, val)

    if (!parent) {
      tree[id] = val
      return [tree, treeMap]
    }

    if (!treeMap.has(parent)) {
      const parentVal = { [id]: val }
      treeMap.set(parent, parentVal)
      tree[parent] = parentVal
      return [tree, treeMap]
    }

    const newParentValue = treeMap.get(parent)
    newParentValue[id] = val
    treeMap.set(parent, newParentValue)
    return [tree, treeMap]
  }, [{}, new Map()])
}

const [result] = buildTree(arrSample)

console.log(JSON.stringify(result, 0, 2))
Answer:2

You could use reduce method for this and store each id on the first level of the object. This solution will work if the objects in the array are in the correct order as in the tree structure.

const data = [{"id":"Futebol","parent":null},{"id":"Ball","parent":"Futebol"},{"id":"Nike","parent":"Ball"},{"id":"Volley","parent":null}]

const result = data.reduce((r, { id, parent }) => {
  if (!parent) {
    r[id] = {}
    r.tree[id] = r[id]
  } else if (r[parent]) {
    r[parent][id] = {}
    r[id] = r[parent][id]
  }

  return r
}, {tree: {}}).tree

console.log(result)
Answer:3

If reduce solution is just an option, you can try this way:

var input = [
  {
    "id": "Ball",
    "parent": "Futebol"
  },
  {
    "id": "Nike",
    "parent": "Ball"
  },
  {
    "id": "Volley",
    "parent": null
  }
];

var output = {};

input.forEach(item => {
  var temp = input.find(x => x.id === item.parent);
  if (temp) {
    temp[item.id] = {};
  }
});

input = input.filter(item => !input.find(x => x.hasOwnProperty(item.id)));

input.forEach(item => {
  if (!item.parent) {
    output[item.id] = {};
  } else {
    for (var [id, value] of Object.entries(item)) {
      if (typeof value === 'object') {
        output[item.parent] = { [item.id]: { id: {} } };
      }
    }
  }
})

console.log(output);
Answer:4

I am currently working on a Meteor application that also has a chat functionality. I want to have a list of all conversations that show the most recent message in each conversation. (Similar to ...

I am currently working on a Meteor application that also has a chat functionality. I want to have a list of all conversations that show the most recent message in each conversation. (Similar to ...

Does anyone knows how to directly call a array key of a Map Object. As shown in below code, I can map.get(arr), but not map.get([0, 1, 2, 3]) const map = new Map() const arr = [0,1,2,3] map....

Does anyone knows how to directly call a array key of a Map Object. As shown in below code, I can map.get(arr), but not map.get([0, 1, 2, 3]) const map = new Map() const arr = [0,1,2,3] map....

  1. call array object javascript
  2. call object array php
  3. call array inside object
  4. call an array object
  5. java call array object
  6. call_user_func_array object
  7. call_user_func_array object method
  8. jni call object array method
  9. call_user_func_array object oriented
  10. call_user_func_array object php
  11. array object call function
  12. python call array object

In my console's browser, when I do : console.log(typeof(typeof)) it returns an error Uncaught SyntaxError: Unexpected token ')' Why is that? Why can't I get typeof's type ?

In my console's browser, when I do : console.log(typeof(typeof)) it returns an error Uncaught SyntaxError: Unexpected token ')' Why is that? Why can't I get typeof's type ?

ul element that has dynamically loaded li a children, sometimes the li a populate empty innerHTML. How do I remove all of the li elements that have an empty a child? Current (errors Uncaught ...

ul element that has dynamically loaded li a children, sometimes the li a populate empty innerHTML. How do I remove all of the li elements that have an empty a child? Current (errors Uncaught ...

  1. javascript remove empty string from array
  2. javascript remove empty lines
  3. javascript remove empty space
  4. javascript remove empty values from object
  5. javascript remove empty objects from array
  6. javascript remove empty space from string
  7. javascript remove empty characters from string
  8. javascript remove empty objects
  9. javascript remove empty tags
  10. javascript remove empty p tags
  11. javascript remove empty slots from array
  12. javascript remove empty in array
  13. javascript remove empty html tags
  14. javascript remove empty paragraphs
  15. javascript remove empty value from array
  16. javascript remove empty rows from table
  17. javascript remove empty item from array
  18. javascript remove empty text nodes
  19. javascript remove empty lines from textarea