使用key将数组转换为ojbect

时间:2015-06-06 07:53:48

标签: javascript arrays underscore.js lodash

我需要使用键值将数组转换为object。我试过一些代码。但没有得到确切的结果。我可以使用lodash或下划线js吗?

array = [
    {
        facebook: 'disneyland',
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
    },
    {
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
        twitter: 'disneyland',
    },
    {
       preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
        linkedin: 'disneyland',
    },
    {
        xing: 'disneyland',
        preview_image_url: ''
    },
    {
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png',
        weibo: 'disneyland'
    } 
]

预期产出

result = {
    facebook: {
        facebook: 'disneyland',
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
    },
    twitter: {
        twitter: 'disneyland',
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
    },
    linkedin: {
        linkedin: 'disneyland',
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
    },
    xing: {
        linkedin: 'disneyland',
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
    },
    weibo: {
        linkedin: 'disneyland',
        preview_image_url: 'http: //amt.in/img/amt_logo_big.png'
    }
}

我试过这个

var newnwcontent = {};
array.forEach(function (network) {
                                var name = Object.keys(network)[0];
                                newnwcontent[name] = network;
                            });

3 个答案:

答案 0 :(得分:2)

您需要检查属性键,无法保证索引0

var newnwcontent = {}

array.forEach(function(el) {
  var keys = Object.keys(el)
  var key = keys[0] == 'preview_image_url' ? keys[1] : keys[0]
  newnwcontent[key] = el
})

答案 1 :(得分:2)

您可以在lodash中使用以下方法:

_.indexBy(array, function(item) {
    return _(item)
        .keys()
        .without('preview_image_url')
        .first();
});

这里,indexBy()基于数组返回一个新对象。传递它的函数告诉它如何构造键。在这种情况下,您可以使用keys()来获取密钥,without()删除不需要的密钥,使用first()来获取值。

答案 2 :(得分:0)

您可以使用此类功能获得所需的结果:

var result = {};
// iterate through all networks
array.forEach(function (network) {
    // iterate through all properties of an array item
    for(var property in network){
        // ignore property preview_image_url
        if(property!=='preview_image_url')
        {
            // any other property is your key, add an item to result object
            result[property] = network;
        }
    }
});
// output the result
console.log(result);