使用 with 键将数组转换为对象

Convert array to ojbect with with key

我需要将数组转换为具有键值的对象。我试过一些代码。但没有得到确切的结果。我可以使用 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;
                            });

您可以使用这样的函数来得到您需要的结果:

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);

您需要检查属性键,索引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
})

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

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

此处,indexBy() returns a new object based on an array. The function you pass it, tells it how to construct the keys. In this case, you use keys() to get the keys, without() to remove what you don't need, and first()获取值。