操作和更改原始数组的键

时间:2015-12-22 04:18:44

标签: javascript lodash

我目前正在处理数组/对象中的项目。我之前没有使用过lodash,但在阅读了这个实用工具提供的功能后,我决定试一试。我想修改的数组涉及添加一个addtional对象sources和更改键。如何使用lodash实现以下目标?

当前数组

var myArr = 
[{
    "flv": "myFile.flvs",
    "mp4": "myFile.mp4",
    "webm": "myFile.webm",
    "thumbnail": "poster.png",
    "title": "Test",
    "id": 123456
}];

期望的结果

{
data: [
    {
        sources: [{ 
            file: "myFile.flv"
        },{ 
            file: "myFile.mp4"
        },{
            file: "myFile.webm"
        }],
        image: 'poster.png',
        title: 'Test',
        id: '123456'
    },
    ....
    ]
}   

1 个答案:

答案 0 :(得分:2)

这个怎么样:

var myArr = {
    "data": [{
        "test1": "myFile.flv",
        "test2": "myFile.mp4",
        "test3": "myFile.webm",
        "thumbnail": "poster.png",
        "title": "Test",
        "id": 123456
    }]
};

var result = _.map(myArr.data, function(el) {
    var sources = []
    _.each(el, function(v, k) {
        if (k.match(/test\d*/) !== null) {
            sources.push({
                file: v
            });
        }
    });
    return {
        sources: sources,
        image: el.thumbnail,
        title: el.title,
        id: el.id
    };
});

console.log(result);

结果:

enter image description here

每个OP请求更新:

var EXTENSIONS = ['flv', 'mp4', 'webm'];
var myArr = [{
        "flv": "myFile.flv",
        "mp4": "myFile.mp4",
        "webm": "myFile.webm",
        "thumbnail": "poster.png",
        "title": "Test",
        "id": 123456
    }];

var result = _.map(myArr, function(el) {
    var sources = [];
    _.each(el, function(v, k) {
        if (_.contains(EXTENSIONS, k)) {
            sources.push({
                file: v
            });
        }
    });
    return {
        sources: sources,
        image: el.thumbnail,
        title: el.title,
        id: el.id
    };
});

console.log(result);

注意:这里我们可以使用_.contains(这是lodash)或EXTENSIONS.indexOf(Javascript原生)。既然你想学习lodash,我想我们使用_.contains。

更新:刚刚从map函数中删除了.data,因为OP从源数据中删除了数据属性。