使用lodash或underscore js基于键集将数组转换为对象

时间:2015-07-16 05:26:32

标签: javascript arrays underscore.js lodash

我需要使用lodash或underscore js根据另一个数组中的值将数组转换为对象。

var connections = [ 'facebook', 'twitter', 'linkedin', 'xing', 'weibo' ];

var contents = [
    {
        preview_image_url: "http://www.ideacellular.com/ISC/images/banners/home-page/banner1.jpg",
        preview_title: "title of the message1",
        facebook: "fb first 22 once more",
        preview_description: "Home↵How to↵How to find a Place in KeralaHow to find a place in Kerala"
    },
    {
        linkedin: "test linkedin",
        preview_image_url: "http://www.ideacellular.com/ISC/images/banners/home-page/banner2.jpg",
        preview_title: "linkedin title2",
        preview_description: "linkedin description 2"
    },
    {
        preview_image_url: "http://www.ideacellular.com/ISC/images/banners/home-page/banner3.jpg",
        preview_title: "linkedin title3",
        preview_description: "linkedin description 3",
        twitter: "test twitter"
    }
];

我的要求是遍历连接数组,如果内容数组中存在任何连接,则使用这些连接名称创建结果ojbect。

预期结果

var result = {
    facebook: {
        preview_image_url: "http://www.ideacellular.com/ISC/images/banners/home-page/banner1.jpg",
        preview_title: "title of the message1",
        facebook: "fb first 22 once more",
        preview_description: "Home↵How to↵How to find a Place in KeralaHow to find a place in Kerala"
    },
    linkedin: {
        linkedin: "test linkedin",
        preview_image_url: "http://www.ideacellular.com/ISC/images/banners/home-page/banner2.jpg",
        preview_title: "linkedin title2",
        preview_description: "linkedin description 2"
    },
    twitter: {
        preview_image_url: "http://www.ideacellular.com/ISC/images/banners/home-page/banner3.jpg",
        preview_title: "linkedin title3",
        preview_description: "linkedin description 3",
        twitter: "test twitter"
    }
};

非常感谢您的帮助。我尝试过使用forEach的常规循环,有没有简单的方法来使用下划线js或lodash。谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个,

var result = {};

connections.forEach(function (key) {
    contents.forEach(function (el) {
        if (el[key] && !result[key]) {
            result[key] = el;
        }
    });
});

console.log(result);

Example

答案 1 :(得分:1)

您可以使用indexBy()intersection()

_.indexBy(contents, function(item) {
    return _(item)
        .keys()
        .intersection(connections)
        .first();
});

我们的想法是找到contents项和connections数组的键之间的交集。如果存在这样的交集,则使用该值作为索引键。