Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 views
in Technique[技术] by (71.8m points)

underscore.js - Underscore to flatten nested array of parent/child objects

I have an array of objects, where each object has a "children" property (example data below). I want to flatten parents/children into a single array, with each parent immediately followed by it's children.

I've written the following using lo-dash / underscore, and it works when I have one and only one child for each parent:

_.flatten(_.zip(myArr, _.flatten(myArr, "children")))

I know I can use something like _.each and build an object, just wondering if there's a snazzy way to do this using _.

Example Data:

[{
    name: "Some Name",
    value: 1234,
    children: [{
        name: "Another name",
        value: 3456
    }, {
        name: "A third name",
        value: 9876
    }]
}, {
    name: "Omg Lazer Guns",
    value: 3333,
    children: [{
        name: "PewPewPew",
        value: 4444
    }]
}];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A simple and more readable way to do this is

var list = [];
_.each(data, function(item){
    list.push(_.omit(item, 'children'));
    list.push(_.flatten(_.pick(item, 'children')));
});
var result = _.flatten(list);

The result is

[{
    "name": "Some Name",
    "value": 1234
}, {
    "name": "Another name",
    "value": 3456
}, {
    "name": "A third name",
    "value": 9876
}, {
    "name": "Omg Lazer Guns",
    "value": 3333
}, {
    "name": "PewPewPew",
    "value": 4444
}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...