telex-wap telex-wap - 3 months ago 9
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) {
updateddata.push({
id: updateddata[i].id,
parent: updateddata[i].parent[0]
})
updateddata[i].parent.shift()
}
}


And it works perfect, except for the fact that when doing
console.log(JSON.stringify(updateddata))
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
console.log
for
updateddata
:

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


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

How could I solve it?

Answer

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: ar.id, parent: e});
  });
  return r;
}, []);

console.log(result)

Comments