telex-wap telex-wap - 1 year ago 49
Javascript Question

Splitting an array remains as array of one item rather than a string

I have a javascript array of objects, where there is a property with another array as value, as seen here:

var data = [
id: 1,
parent: [1,2,3,4]
id: 2,
parent: [5,6,7,8]

I am trying to split it, so every object with more than one parent, gets a duplicated copy of itself, each copy with a different parent. I have done this so far:

var updateddata = JSON.parse(JSON.stringify(data));

for (var i = 0; i < updateddata[i].parent.length; i++) {
while (updateddata[i].parent.length > 1) {
id: updateddata[i].id,
parent: updateddata[i].parent[0]

And it works perfect, except for the fact that when doing
I can see that the first two entries have as a parent an array with one single entry, unlike the others, which are already outside the array:

This is the


I have also tried to use
in the values, but it didn't make any difference.

How could I solve it?

Answer Source

You could do this with reduce() and forEach() loop

var data = [{
  id: 1,
  parent: [1, 2, 3, 4]
}, {
  id: 2,
  parent: [5, 6, 7, 8]

var result = data.reduce(function(r, ar) {
  ar.parent.forEach(function(e) {
    r.push({id:, parent: e});
  return r;
}, []);