Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  122] [ 7]  / answers: 1 / hits: 27700  / 9 Years ago, thu, june 4, 2015, 12:00:00

I have array of objects like this:



var data = [
{
type : parent,
name : A
},
{
type : child,
name : 1
},
{
type : child,
name : 2
},
{
type : parent,
name : B
},
{
type : child,
name : 3
}
]


and I want to move child objects into parent objects, splitted by the parrent object (there is no given key from child object is belonged to which parrent). So it's only separate by the parent object. To be simple I want to change the array into :



[
{
type : parent,
name : A,
child: [
{
type : child,
name : 1
},
{
type : child,
name : 2
}
]
},
{
type : parent,
name : B,
child: [
{
type : child,
name : 3
}
]
}
]


I have read lodash about chunk but it's no use.


More From » arrays

 Answers
208

You can use either the native Array.prototype.reduce function or lodash's reduce:





var data = [{
type: parent,
name: A
},
{
type: child,
name: 1
},
{
type: child,
name: 2
},
{
type: parent,
name: B
},
{
type: child,
name: 3
}
];

// If using _.reduce then use:
// var newData = _.reduce(data, function(arr, el) {...}, []);
var newData = data.reduce(function(arr, el) {
if (el.type === 'parent') {
// If el is pushed directly it would be a reference
// from the original data object
arr.push({
type: el.type,
name: el.name,
child: []
});
} else {
arr[arr.length - 1].child.push({
type: el.type,
name: el.name
});
}

return arr;
}, []);

console.log(newData);





UPDATE: Small changes using newer ES language features





const data = [{
type: parent,
name: A
},
{
type: child,
name: 1
},
{
type: child,
name: 2
},
{
type: parent,
name: B
},
{
type: child,
name: 3
}
];

const newData = data.reduce((arr, el) => {
if (el.type === 'parent') {
// If el is pushed directly it would be a reference
// from the original data object
arr.push({...el, child: []});
} else {
arr[arr.length - 1].child.push({...el});
}

return arr;
}, []);

console.log(newData);




[#66329] Wednesday, June 3, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patienceannel

Total Points: 674
Total Questions: 101
Total Answers: 101

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
patienceannel questions
Fri, Mar 11, 22, 00:00, 2 Years ago
Tue, Oct 20, 20, 00:00, 4 Years ago
Wed, Jul 24, 19, 00:00, 5 Years ago
;