在javascript中转换Array对象(nodejs + mysql + sequelize)

时间:2017-11-29 10:22:26

标签: javascript mysql node.js

这是我的json对象:

   {
    excels:
       [ { field1: '123456789',
           field2: 'Mohamed',
           field3: 'Sameer'},

         { field1: '111111111',
           field2: 'Hameed',
           field3: 'Basha'},

         { field1: '222222222',
           field2: 'Mohamed',
           field3: 'Basha'} ],

      header:
       { '0': 'gsm',
         '1': 'firstName',
         '2': 'lastName'
    }

}

如何将其转换为:

[{gsm:123456789;firstName:'Mohamed';lastName:'Sameer'},{gsm:111111111;firstName:'Hameed';lastName:'Basha'},{gsm:222222222;firstName:'Mohamed';lastName:'Basha'}]

是否可以进行此类转换?

帮帮我,我是新手!

2 个答案:

答案 0 :(得分:2)

我认为使用lodash.mapKeys

会更加清晰
const mapKeys = require('lodash.mapkeys');

const arr = obj.excels.map(
  (excel) => {
    const keys = Object.values(obj.header)
    return mapKeys(excel, (value, key) => keys.shift())
  }
);

console.log(arr);

答案 1 :(得分:0)



let obj = {
excels:
   [ { field1: '123456789',
       field2: 'Mohamed',
       field3: 'Sameer'},

     { field1: '111111111',
       field2: 'Hameed',
       field3: 'Basha'},

     { field1: '222222222',
       field2: 'Mohamed',
       field3: 'Basha'} ],

  header:
   { '0': 'gsm',
     '1': 'firstName',
     '2': 'lastName',
     '3': 'street'} 
}

let targetObj = [];
let keysLength = Object.keys(obj["excels"][0]).length;
for(i=0;i< keysLength;i++) {
    targetObj[i] = {};
    let key = obj["header"][i]
    targetObj[i]['gsm'] = obj["excels"][i]["field1"];
    targetObj[i]['firstName'] = obj["excels"][i]["field2"];
    targetObj[i]['lastName'] = obj["excels"][i]["field3"];
}

console.log(targetObj)
&#13;
&#13;
&#13;