对于那里的lodash专家来说是一个挑战: 我正在改变这种数据结构:
{
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'
}
进入这一个:
[{
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'
}
}]
有一些杂乱的代码,但我想要的是能够用一些lodash魔法以优雅的方式做到这一点。因此,如果有人愿意展示他们的lodash技能,那将是值得赞赏的:我已经尝试过并且未能提出一个像样的代码......
答案 0 :(得分: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>
答案 1 :(得分: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));
&#13;
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
&#13;