2016-10-27 9 views
0

そこlodashの専門家のための挑戦:いくつかの厄介なコードでlodashデータ操作挑戦

[{ 
    id: 71, 
    data: { 
     caption: 'lounge', 
     description: 'View of the lounge from the kitchen' 
    } 
}, { 
    id: 72, 
    data: { 
     caption: 'whatever', 
     description: 'Some description of the whatever photo shown' 
    } 
}] 

しかし、私は希望:この一つに

{ 
file_caption_71: 'lounge', 
file_description_71: 'View of the lounge from the kitchen', 
file_caption_72: 'whatever', 
file_description_72: 'Some description of the whatever photo shown' 
} 

: 私はそのデータ構造を回していますそれはエレガントなやり方でロダッシュの魔法を使って行うことができるということです。だから誰もが認識できるロダッシュのスキルを表示したい場合:私は試してみたし、まともな外観のコードを考え出すことができませんでした...

答えて

0

_.transform()を使用してオブジェクトを新しいマップオブジェクトに変更するIDは、その後、値を使用してアレイにサブオブジェクトを抽出:

var data = { 
 
    file_caption_71: 'lounge', 
 
    file_description_71: 'View of the lounge from the kitchen', 
 
    file_caption_72: 'whatever', 
 
    file_description_72: 'Some description of the whatever photo shown' 
 
}; 
 

 
var result = _(data).transform(function(result, value, key) { 
 
    var keys = key.split('_'); 
 
    var id = keys[2]; 
 
    var dataType = keys[1]; 
 
    
 
    result[id] = result[id] || { id: parseInt(id, 10), data: {} }; 
 
    
 
    result[id].data[dataType] = value; 
 
    
 
    return result; 
 
}).values().value(); 
 

 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

0

const data = { 
 
    file_caption_71: 'lounge', 
 
    file_description_71: 'View of the lounge from the kitchen', 
 
    file_caption_72: 'whatever', 
 
    file_description_72: 'Some description of the whatever photo shown' 
 
}; 
 

 

 
const extract = (data) => { 
 
    const _finalResult = _.reduce(data, (result, value, key) => { 
 
    const [prefix, type, id] = key.split('_'); 
 
    _.set(result, `${id}.${type}`, value); 
 
    return result; 
 
    }, {}); 
 

 
    return _.map(_finalResult, (data, id) => ({id, data})); 
 
} 
 

 
console.log('result', extract(data));
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

関連する問題