Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I feel that there must be a better way to "expand out" JavaScript objects based on an array of one of the properties. Here is the sample code that works and achieves the correct result but it's as ugly as sin and doesn't feel right.

"use strict";

var _ = require('lodash');

var test = [
    {
        some: 'value',
        somestuff: ['one','two','three']
    },
    {
        some: 'other value',
        somestuff: 'four'
    }
];

var result = _.map(test,function(item){
    if(Array.isArray(item.somestuff)){
        var myarray = item.somestuff;
        delete item.somestuff;
        return _.map(myarray, function(item2){
            var newItem = _.cloneDeep(item);
            newItem.ar = item2;
            return newItem;
        });
    } else {
        return item;
    }
});

var hyperresult = _.flatten(result);

console.log(hyperresult);
share|improve this question
    
codereview.stackexchange.com ? –  Felix Kling Jun 17 at 5:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.