数组对象重组

时间:2017-05-31 09:35:37

标签: javascript

我有这样的Javascript对象:

var value=[ RowDataPacket {options: 'card_img_url',options_value: 'https://ttest.com/logo.png' },RowDataPacket {options: 'card_img_url',    options_value: 'https://ttest.com/logo2.png' },RowDataPacket {options: 'card_description', options_value: 'card 1 desc ' },RowDataPacket {    options: 'card_description',options_value: 'card 2 desc' },RowDataPacket {
options: 'card_footer',options_value: 'card 1 footer' },RowDataPacket {
options: 'card_footer', options_value: 'card 2 footer' }];

var shaym = [];             
for(var i=0; i<value.length; i++){ 
var itemoptions = value[i].options;
var itemoptionsval = value[i].options_value;             
var temp = {};
temp[itemoptions] = itemoptionsval;
shaym.push(temp); 

}

console.log(shaym);

显示 -

[{ card_img_url: 'https://ttest.com/logo.png' },{ card_img_url: 'https://ttest.com/logo2.png' },{ card_description: 'card 1 desc ' },{ card_description: 'card 2 desc' },{ card_footer: 'card 1 footer' },{ card_footer: 'card 2 footer' } ]

形成上面的代码我想要这个类型的对象: [{card_img_url:&#39; https://ttest.com/logo.png&#39;,card_description:&#39; card 1 desc&#39;,card_footer:&#39; card 1 footer&#39;},{card_img_url:& #39; https://ttest.com/logo2.png&#39;,card_description:&#39; card 2 desc&#39;,card_footer:&#39; card 2 footer&#39;}]

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以检查对象的键是否与上一个对象的键相同。如果相同,则获取结果数组的下一个索引,否则为零。然后将对象分配给结果集。

var data = [{ card_img_url: 'https://ttest.com/logo.png' }, { card_img_url: 'https://ttest.com/logo2.png' }, { card_description: 'card 1 desc ' }, { card_description: 'card 2 desc' }, { card_footer: 'card 1 footer' }, { card_footer: 'card 2 footer' }],
    result = data.reduce(function (last, i) {
        return function (r, a) {
            var k = Object.keys(a)[0];
            i = k === last ? i + 1 : 0;
            r[i] = r[i] || {};
            r[i][k] = a[k];
            last = k;
            return r;
        };
    }(), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }